sql - 按一列分组并在多个条件下返回多列 - T-SQL
问题描述
我有两个可以使用 SELECT 语句(连接多个表)生成的表,如下所示:
表格1:
ID | 地点 | 类型 | 时间 |
---|---|---|---|
1 | 达拉斯 | 2 | 01-01-2021 |
2 | 丹佛 | 1 | 02-01-2021 |
3 | 芝加哥 | 1 | 03-01-2021 |
4 | 芝加哥 | 2 | 29-11-2020 |
5 | 丹佛 | 1 | 28-02-2020 |
6 | 多伦多 | 2 | 11-05-2019 |
表 2:
ID | 地点 | 集 | 存入 |
---|---|---|---|
1 | 丹佛 | 无效的 | 29-01-2021 |
2 | 丹佛 | 01-04-2021 | 29-01-2021 |
3 | 芝加哥 | 无效的 | 19-01-2020 |
4 | 达拉斯 | 无效的 | 29-01-2019 |
5 | 温尼伯 | 13-02-2021 | 17-01-2021 |
6 | 多伦多 | 14-02-2020 | 29-01-2020 |
我希望按站点对结果进行分组,在每列上都有 type=1 的 COUNT,type=2,存放和收集,所有 4 列在选定的时间间隔之间。示例:(01-06-2020 和 01-06-2021 之间的时间间隔:
地点 | 类型1 | 类型2 | 存入 | 集 |
---|---|---|---|---|
达拉斯 | 0 | 1 | 0 | 0 |
丹佛 | 1 | 0 | 2 | 1 |
芝加哥 | 1 | 1 | 0 | 0 |
多伦多 | 0 | 0 | 0 | 0 |
温尼伯 | 0 | 0 | 1 | 1 |
解决方案
union all
和聚合怎么样?
select site,
sum(case when type = 1 then 1 else 0 end) as type_1,
sum(case when type = 2 then 1 else 0 end) as type_2,
sum(deposited) as deposited, sum(collected) as collected
from ((select site, type, 0 as deposited, 0 as collected
from table1
) union all
(select site, null,
(case when deposited is not null then 1 else 0 end),
(case when collected is not null then 1 else 0 end)
from table2
)
) t12
group by site;
推荐阅读
- elasticsearch - 如何将最新内容与 Elasticsearch 混合?
- javascript - 如何在 Firebase 中多次使用查询?
- amazon-web-services - 如何查看/监控 AWS Site-to-Site VPN 的数据包(传入/传出)
- sql - 将新成绩添加到数据库时,Microsoft sql 会触发自动更新 GPA
- agora.io - 录制 Agora 时只获得一个屏幕
- performance - Pytorch(GPU)中(低秩块)对角线与向量的有效乘法
- html - 如何使用 CSS 插入 LUI 图标“向下箭头”
- android - 如何从 Kotlin Android 应用程序连接到 Phoenix 频道?
- php - 如何使 smtp 设置为动态的?我收到一个错误参数 1 传递给 Illuminate\Mail\MailManager::getConfig()
- reactjs - 如何为我的对象中的每个数组项添加 2 个新属性