【问题标题】:Count rows within each group when condition is satisfied Sql Server满足条件时计算每个组中的行数Sql Server
【发布时间】:2020-04-10 21:51:19
【问题描述】:

我的桌子如下所示:

         ID            Date     IsFull
         1          2020-01-05    0 
         1          2020-02-05    0  
         1          2020-02-25    1  
         1          2020-03-01    1
         1          2020-03-20    1

我想显示 ID = 1 的月份数

在给定月份中 sum(isfull)/count(*) > .6(该月超过 60% 的时间 isfull = 1)

所以最终的输出应该是

 ID     HowManyMonths
  1       1     --------(Only month 3----2 out 2 cases)

如果问题变为 sum(isfull)/count(*) > .4

那么最终的输出应该是

  ID     HowManyMonths
   1       2     --------(Month 2 and Month 3)

谢谢!!

【问题讨论】:

    标签: sql sql-server tsql date group-by


    【解决方案1】:

    您可以通过两个级别的聚合来做到这一点:

    select id, count(*) howManyMonths
    from (
        select id
        from mytable
        group by id, year(date), month(date)
        having avg(1.0 * isFull) > 0.6
    ) t
    group by id
    

    子查询按 id、年份和月份聚合,并使用 having 子句过滤满足成功率的组(avg() 很方便)。外部查询计算每个 id 的目标比率通过了多少个月。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2018-07-26
      • 2015-03-21
      • 1970-01-01
      相关资源
      最近更新 更多