如何从午夜开始的不同时间开始按日期分组?

时间:2012-07-23 15:21:08

标签: sql

如果可能,我想在一个声明中这样做。

我原来的疑问是:

SELECT CAST(Date as DATE) as DayDate, SUM(Books) as LostBooks 
FROM RestartBooksView 
WHERE Name = 'AUHT167' and Date > (getdate() - 105) 
GROUP BY CAST(Date as DATE) 
ORDER BY CAST(Date as DATE) ASC

此查询的问题在于,我希望汇总在上午7点到早上7点反映,而不是当前上午12点到12点。如何修改我的查询以反映此更改?

1 个答案:

答案 0 :(得分:3)

假设列“date”实际上是一个日期时间。

SELECT CAST(Date as DATE) as DayDate, SUM(Books) as LostBooks
FROM (select rbv.*,
             cast(dateadd(h, -7, date) as date) as newdate
      from RestartBooksView rbv
     )
WHERE Name = 'AUHT167' and newdate > (getdate() - 105)
GROUP BY newdate
ORDER BY CAST(Date as DATE) ASC

我还使用了SQL Server日期函数,因为您似乎正在使用该数据库。