【问题标题】:Group by one column and return several columns on multiple conditions - T-SQL按一列分组并在多个条件下返回多列 - T-SQL
【发布时间】:2021-10-05 08:32:24
【问题描述】:

我有两个表,可以使用 SELECT 语句(连接多个表)生成如下:

表 1:

ID Site type time
1 Dallas 2 01-01-2021
2 Denver 1 02-01-2021
3 Chicago 1 03-01-2021
4 Chicago 2 29-11-2020
5 Denver 1 28-02-2020
6 Toronto 2 11-05-2019

表 2:

ID Site collected deposited
1 Denver NULL 29-01-2021
2 Denver 01-04-2021 29-01-2021
3 Chicago NULL 19-01-2020
4 Dallas NULL 29-01-2019
5 Winnipeg 13-02-2021 17-01-2021
6 Toronto 14-02-2020 29-01-2020

我希望按站点对结果进行分组,在每列上都有 type=1 的 COUNT,type=2,存放和收集,所有 4 列在选定的时间间隔之间。示例:(01-06-2020 和 01-06-2021 之间的时间间隔:

Site type1 type2 deposited collected
Dallas 0 1 0 0
Denver 1 0 2 1
Chicago 1 1 0 0
Toronto 0 0 0 0
Winnipeg 0 0 1 1

【问题讨论】:

  • 只有两种类型吗?
  • 多伦多为什么有两个0s?
  • 因为包裹是2020年初存取的,超出了选择的区间
  • Martin,表中有多种类型

标签: sql sql-server tsql


【解决方案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;

【讨论】:

  • 我正在努力将其应用到我的上下文中。 t12 代表什么?
  • 另外,我应该在哪里添加时间限制?在 FROM 子句中的每个 select 语句中,还是只有一次,就在 GROUP BY 之前?
  • 我想我已经成功地应用了这个,但是我收到一条错误消息,指出“操作数数据类型 datetime 对 sum 运算符无效”。我相信它不想总结存放和收集的日期。我尝试过使用 COUNT,但它也返回了一个错误,指出“无法对包含聚合或子查询的表达式执行聚合函数”
  • @Tucker。 . .它是一个表别名,FROM 子句中的子查询需要它。您可以将时间限制添加到子查询。我解决了最后一个问题。
  • 谢谢Gordon,解决了。最后一个问题。是否可以在type2的count小于type1的80%,并且当收集到的小于deposit的80%时有flag?
【解决方案2】:
  • 将表 1 和表 2 与站点上的连接组合起来
  • 对类型 2 使用 COUNT(CASE WHEN type = 1 then 1 END) as type1 和类似的构造
  • 使用COUNT(CASE WHEN somedate BETWEEN '2020-06-01' and '2021-06-01' then 1 END) as ... 作为您的日期

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2013-08-05
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多