[英]T-SQL Crosstab count query
If have the following dataset:如果有以下数据集:
... and I want to do a crosstab of sorts, counting the data against specific criteria eg: ...我想做一个交叉表,根据特定标准计算数据,例如:
Colour criteria : String contains "Blue", "Red", "Yellow" or "Green" (not case sensitive)颜色标准:字符串包含“Blue”、“Red”、“Yellow”或“Green”(不区分大小写)
Type criteria : String contains "Car", "Lorry", or "Bus (not case sensitive)类型标准:字符串包含“Car”、“Lorry”或“Bus”(不区分大小写)
... and I would like the result to look like the following: ...我希望结果如下所示:
Is there an SQL query that I can run on the original data to produce the result I'm looking for?是否有我可以对原始数据运行的 SQL 查询来生成我正在寻找的结果?
With conditional aggregation:使用条件聚合:
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
See the demo .请参阅演示。
Results:结果:
> colour | Car | Lorry | Bus
> :----- | --: | ----: | --:
> Blue | 3 | 1 | 0
> Red | 1 | 2 | 0
> Yellow | 0 | 1 | 1
> Green | 0 | 0 | 2
You can use CROSS APPLY
with conditional aggregation;您可以将CROSS APPLY
与条件聚合一起使用; CROSS APPLY
simplifies the generation of the list of colours: 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
Output:输出:
colour Car Lorry Bus
Blue 3 1 0
Red 1 2 0
Yellow 0 1 1
Green 0 0 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.