1

我是新手,我有一张像下面这样的桌子。我需要检索如下结果的数据。你能建议如何得到这个结果吗?

我想要这样的结果:

date count(ref_no) count(ctn_no) sum(quantity)

00:00am to 08:00 4 5 10000

08:01am to 12:00pm

12:01pm to 18:00pm
18:01 to 23:59pm 00 00 000


tbl_pack
insert_date ref_no ctn_no serial_no quantity

03/09/2012 13:12:53:837 I2280097 34 1 T3BSB 500
03/09/2012 13:12:53:867 I2280097 34 2 T3BSA 500
03/09/2012 13:12:53:893 I2280097 34 3 T3BS9 500
03/09/2012 13:12:53:923 I2280097 34 4 T1NJR 500
03/09/2012 13:13:37:453 I2280097 35 1 T29KU 2000
03/09/2012 13:13:37:483 I2280097 35 2 T29KT 2000
03/09/2012 13:13:37:51 I2280097 35 3 T29KS 2000
03/09/2012 13:25:11:907 I2280102 1 1 T491Q 400
03/09/2012 13:25:11:953 I2280102 1 2 T491S 400
03/09/2012 13:25:11:983 I2280102 1 3 T491U 400
4

1 回答 1

0

我对表字段的重命名略有不同,因为我不完全知道如何解释提供的数据中的字段,所以我的示例查询解决方案可能与您的预期不完全一致,但应该很接近。我怀疑您还想显示实际的 RefNumber,也许还有 CartonNumber,但这只是猜测。

tbl_pack: CalendarDateTime RefNumber CartonNumber SequenceNumber SerialNumber Quantity
3/9/2012 13:12:53:837 I2280097 34 1 T3BSB 500
3/9/2012 13:12:53:867 I2280097 34 2 T3BSA 500
3/9/2012 13:12:53:893 I2280097 34 3 T3BS9 500
3/9/2012 13:12:53:923 I2280097 34 4 T1NJR 500
3/9/2012 13:13:37:453 I2280097 35 1 T29KU 2000
3/9/2012 13:13:37:483 I2280097 35 2 T29KT 2000
3/9/2012 13:13:37:510 I2280097 35 3 T29KS 2000
3/9/2012 13:25:11:907 I2280102 1 1 T491Q 400
3/9/2012 13:25:11:953 I2280102 1 2 T491S 400
3/9/2012 13:25:11:983 I2280102 1 3 T491U 400

然后这个查询将做你所要求的:

SELECT  
    CONVERT(varchar(10), CalendarDateTime, 111),  
    (  
        CASE   
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) <= 8*60 THEN '0:00am To 8:00am'  
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) between 8*60 + 1 and 12*60 THEN '8:00am To 12:00pm'  
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) between 12*60 + 1 and 18*60 THEN '12:00pm To 18:00pm'  
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) between 18*60 + 1 and 24 * 60 - 1 THEN '6:00pm To 23:59pm'  
        END  
    ) as TimePeriod,  
    COUNT(RefNumber) as CountRefNumber,  
    COUNT(CartonNumber) as CountCartonNumber,  
    SUM(Quantity) as SumQuantity 
FROM tbl_pack  
GROUP BY  
    CONVERT(varchar(10), CalendarDateTime, 111),   
    (  
        CASE   
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) <= 8*60 THEN '0:00am To 8:00am'  
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) between 8*60 + 1 and 12*60 THEN '8:00am To 12:00pm'  
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) between 12*60 + 1 and 18*60 THEN '12:00pm To 18:00pm'  
            WHEN datepart(hh,CalendarDateTime) * 60 + datepart(mi,CalendarDateTime) between 18*60 + 1 and 24 * 60 - 1 THEN '6:00pm To 23:59pm'  
        END  
    )
于 2012-12-14T05:08:32.317 回答