SQL

如下表,如何按照时间段进行汇总统计
品号     前期欠料    当天--7天欠料   7天---14天欠料  14天---21天的欠料  品号                        需求数量  需求日期
00-0177000001        7309 20101111
00-0177000001        9540 20101031
00-0177000002        46110 20101031
00-0177000002        35324 20101111
02-0023000005        282 20101106
02-0023000008        687 20101020
02-0023000008        15 20101022
02-0023000008        937 20101024
02-0023000009        3 20101024
02-0023000009        5 20101022
02-0023000009        2 20101020
02-0023000011        774 20101020
02-0023000011        2647 20101022
02-0023000011        2031 20101024
02-0023000012        11 20101024
02-0023000012        15 20101022
02-0023000012        7 20101020
02-0023000013        3 20101020
02-0023000013        6 20101022
02-0023000013        5 20101024
02-0023000014        5 20101024
02-0023000014        6 20101022
02-0023000014        3 20101020
02-0023000015        3 20101020
02-0023000015        6 20101022
02-0023000015        5 20101024
02-0023000016        252 20101024
02-0023000016        477 20101022
02-0023000016        3 20101020
02-0023000017        3 20101020
02-0023000017        6 20101022
02-0023000017        5 20101024
02-0024100008        282 20101106
02-0025100002        1844 20101024
02-0025100002        29 20101022
02-0025100002        1374 20101020
02-0025100003        2 20101020
02-0025100003        5 20101022
02-0025100003        36 20101024
02-0025100004        48 20101024
02-0025100004        5 20101022
02-0025100004        172 20101020

解决方案 »

  1.   

    select 品号,
           sum(case when datediff(day,getdate(),需求日期) < 1 then 需求数量 else 0 end) [前期欠料],
           sum(case when datediff(day,getdate(),需求日期) between 0  and 7 then 需求数量 else 0 end) [当天--7天欠料],
           sum(case when datediff(day,getdate(),需求日期) between 8  and 14 then 需求数量 else 0 end) [7天---14天欠料],
           sum(case when datediff(day,getdate(),需求日期) between 15 and 21 then 需求数量 else 0 end) [14天---21天的欠料]
    from tb
    group by  品号