首页 > 解决方案 > 按一列分组并在多个条件下返回多列 - 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

标签: sqlsql-servertsql

解决方案


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;

推荐阅读