我对表字段的重命名略有不同,因为我不完全知道如何解释提供的数据中的字段,所以我的示例查询解决方案可能与您的预期不完全一致,但应该很接近。我怀疑您还想显示实际的 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
)