我的数据来自04/01/2012 00:00至05/01/2012 05:00
让我们说
StartDate Value
04/01/2012 00:00 10
04/01/2012 05:00 10
04/01/2012 08:00 10
05/01/2012 01:00 10
05/01/2012 04:00 10
05/01/2012 05:00 10
如果我按日期分组
SUM(Value)...
GROUP BY YEAR(StartDate), MONTH(StartDate),DAY(StartDate)
此组数据从04/01/2012 00:00到05/01/2012 00:00并且总和全天值即30
但我需要按时间分组
即04/01/2012 04:00至05/01/2012 04:00以便结果为40
如何实现这一目标。任何人之前都这样做过......
答案 0 :(得分:5)
SUM(Value)
...
GROUP BY CAST(DATEADD(hour, -4, MyDateCol) AS Date)
答案 1 :(得分:2)
select dateadd(hh, 4, date) as date, total from (
select
dateadd(dd, datediff(dd, 0, dateadd(hh, -4, startDate)), 0) as date,
sum(value) as total
from yourTable
group by dateadd(dd, datediff(dd, 0, dateadd(hh, -4, startDate)), 0)
) t
结果:
date total
2012-01-03 04:00:00.000 10
2012-01-04 04:00:00.000 30
2012-01-05 04:00:00.000 20