SQL查询中的存储桶

时间:2018-09-11 13:18:27

标签: sql tsql

我有一个表,该表具有成员ID以及LM_Conversion_date和retired_date。我设法得到了两个日期之间的差额,但现在我想拥有一个老化的存储桶,并反映那些存储在该存储桶下的会员编号。这是我的表格示例,以及我想如何查看数据,

Member_no   LM_Conversion_date  Retired_date    Date_difference
100026            08/12/2017    31/12/2017      23
100114            31/08/2017    31/08/2017      0
100620            15/09/2017    30/09/2017      15
100726             10/01/2017   31/12/2016     -10

我希望输出为

All negative      0-15      15-30     >30
100726            100114    100026   
                  100620        

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合来做到这一点:

select max(case when grp = '<0' then member_no end) as all_negative,
       max(case when grp = '<=15' then member_no end) as [0-15],
       max(case when grp = '<=30' then member_no end) as [15-30],
       max(case when grp = '>30' then member_no end) as [>30]      
from (select t.*, v.grp,
             row_number() over (partition by grp order by member_no) as seqnum
      from t cross apply
           (values (case when date_difference <= 0 then '<0'
                         when date_difference <= 15 then '<=15'
                         when date_difference <= 30 then '<=30'
                         else '>30'
                    end)
           ) v(grp)
      ) t
group by seqnum
order by seqnum;

子查询基本上枚举每个组中的成员。通过汇总将这些汇总到单独的行中。