2011-01-25 62 views
2

需要填写天数列表,并按天记录每天的记录数 。 这是我的问题: 在午夜后录制的所有数据都将在第二天显示: 我需要它转到前一天。访问SQL查询 - 按日期范围分组(按照午夜问题)

我尝试这样做:

SELECT RecordedOnDate, COUNT(RecordedOnDate) AS RowCount, COUNT(SongID) AS [Total Amount] 
FROM InfoTable 
WHERE (RecordedOnDate > DateAdd('h', 5, #1/23/2011#)) AND (RecordedOnDate < DateAdd('h', 5, #1/24/2011#)) 
GROUP BY RecordedOnDate 
ORDER BY RecordedOnDate DESC 

但不能GROUP BY 感谢

回答

2

你想要做什么是由5小时偏移时间,使他们在前一天的“出现”。

SELECT 
    DateAdd('h', -5, RecordedOnDate) RecordedOnDate, 
    COUNT(RecordedOnDate) AS RowCount, 
    COUNT(SongID) AS [Total Amount] 
FROM InfoTable 
WHERE (RecordedOnDate > DateAdd('h', 5, #1/23/2011#)) AND (RecordedOnDate < DateAdd('h', 5, #1/24/2011#)) 
GROUP BY DateAdd('h', -5, RecordedOnDate) 
ORDER BY RecordedOnDate DESC 

解决您的WHERE子句,根据您的需要,但它会由上午05时至凌晨5点组,第二天为“今天”

+0

+1,不需要在GROUP BY如果选择只有一天的`where` – Andomar 2011-01-25 23:08:09

0

将这项工作?我正在尝试先移位,然后按移位和四舍五入的日期进行聚合。添加/更新WHERE子句以筛选感兴趣的日期范围。

;WITH Shifted(sday, smonth, syear) 
AS (
    SELECT 
    DatePart(day, DateAdd('h', -5, RecordedOnDate)) sday, 
    DatePart(month, DateAdd('h', -5, RecordedOnDate)) smonth, 
    DatePart(year, DateAdd('h', -5, RecordedOnDate)) syear 
    FROM Table 
) 
SELECT 
    -- recreate the date 
    DateAdd(day, sday - 1, DateAdd(month, smonth - 1, DateAdd(Year, syear - 1900, 0))) RD, 
    -- aggregate the count for the shifted date 
    COUNT(*) 
FROM Shifted 
GROUP BY 
    DateAdd(day, sday - 1, DateAdd(month, smonth - 1, DateAdd(Year, syear - 1900, 0)))