首页 > 解决方案 > T-SQL 交叉表计数查询

问题描述

如果有以下数据集:

在此处输入图像描述

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

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

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

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

在此处输入图像描述

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

标签: sqlpivot-tablecrosstabcharindex

解决方案


使用条件聚合:

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

请参阅演示
结果:

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

推荐阅读