sql - T-SQL 交叉表计数查询
问题描述
如果有以下数据集:
...我想做一个交叉表,根据特定标准计算数据,例如:
颜色标准:字符串包含“Blue”、“Red”、“Yellow”或“Green”(不区分大小写)
类型标准:字符串包含“Car”、“Lorry”或“Bus(不区分大小写)
...我希望结果如下所示:
是否有一个我可以在原始数据上运行的 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
请参阅演示。
结果:
> colour | Car | Lorry | Bus
> :----- | --: | ----: | --:
> Blue | 3 | 1 | 0
> Red | 1 | 2 | 0
> Yellow | 0 | 1 | 1
> Green | 0 | 0 | 2
推荐阅读
- java - 处理来自系统的警报并不总是显示,selenium web driver java
- javascript - 如何使用'slice'在javascript中获取数组的一部分?
- mongodb - MongoDB $sort 使用聚合真的很慢
- java - Selenium 的 Chrome 网络驱动程序在登录时卡住了
- javascript - 如何在 Angular 7 应用程序中更新 RXJS6 后从 bundle.js 修复“未定义导出/要求”
- google-bigquery - BigQuery 标准 SQL - 将查询或 UDF 存储在表中
- javascript - 如何通过 id 从数组中选择对象?
- postman - 如何使用嵌入文件创建邮递员多部分/表单数据请求?
- swift - 如何使用 AVPlayer 同时播放多个音频文件?
- python - 如何为具有自定义管道的自定义估计器运行网格搜索?