查询数据时间和时间计算总纸箱数

时间:2012-12-14 04:28:41

标签: sql-server sql-server-2008 select

我是新手,我有一张如下表所示的表。我需要检索如下结果的数据。你能告诉我如何得到这个结果吗?

我想要一个这样的结果:

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

1 个答案:

答案 0 :(得分: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  
    )