T-SQL交叉表计数查询

T-SQL Crosstab count query

如果有以下数据集:

...我想做一个交叉表,根据特定标准计算数据,例如:

颜色标准:字符串包含"Blue"、"Red"、"Yellow"或"Green"(不区分大小写)

类型标准:字符串包含 "Car"、"Lorry" 或“总线(不区分大小写)

... 我希望结果如下所示:

是否有一个 SQL 查询,我可以 运行 对原始数据生成我正在寻找的结果?

有条件聚合:

select c.colour,
  count(case when t.VehicleData like '%Car%' then 1 end) Car,
  count(case when t.VehicleData like '%Lorry%' then 1 end) Lorry,
  count(case when t.VehicleData like '%Bus%' then 1 end) Bus
from (
  select 'Blue' colour union all 
  select 'Red' union all
  select 'Yellow' union all
  select 'Green'
) c left join tbl1 t
on t.VehicleData like '%' + c.colour + '%'
group by c.colour

参见demo
结果:

> colour | Car | Lorry | Bus
> :----- | --: | ----: | --:
> Blue   |   3 |     1 |   0
> Red    |   1 |     2 |   0
> Yellow |   0 |     1 |   1
> Green  |   0 |     0 |   2

您可以将 CROSS APPLY 用于条件聚合; CROSS APPLY 简化颜色列表的生成:

select c.colour,
  sum(case when v.VehicleData like '%Car%' then 1 else 0 end) Car,
  sum(case when v.VehicleData like '%Lorry%' then 1 else 0 end) Lorry,
  sum(case when v.VehicleData like '%Bus%' then 1 else 0 end) Bus
from vehicles v
cross apply (values ('Blue'), ('Red'), ('Yellow'), ('Green')
) AS c(colour)
where v.VehicleData like '%' + c.colour + '%'
group by c.colour

输出:

colour  Car Lorry   Bus
Blue    3   1       0
Red     1   2       0
Yellow  0   1       1
Green   0   0       2

Demo on dbfiddle