我有一个查询,它返回从星期一开始的一周的所有记录。我试图获得一周中每一天的记录数而没有成功。
原始查询:
SET DATEFIRST 1 -- Beginning of week is Monday
SELECT DateTime, ScanPoints, PostPoints
FROM SmartTappScanLog
WHERE DateTime >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND DateTime < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
AND UserID = '1' AND BeerID = '3'
ORDER BY DateTime ASC
我尝试了一些事情,包括Count(DateTime)和Group By:
SET DATEFIRST 1 -- Beginning of week is Monday
SELECT Count(DateTime), ScanPoints, PostPoints
FROM SmartTappScanLog
WHERE DateTime >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND DateTime < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
AND UserID = '1' AND BeerID = '3'
ORDER BY DateTime ASC
GROUP BY DateTime
错误表示GROUP附近存在语法错误。
答案 0 :(得分:2)
您的查询有一些问题,
选中的非聚合列也必须位于GROUP BY子句
中SELECT Count(DateTime), ScanPoints, PostPoints...
GROUP BY ScanPoints, PostPoints
我假设您的列DateTime实际上包含日期和时间。分组通过此,将为您提供数据中每个唯一日期/时间值的记录。由于您需要每日数据,因此您应该将时间转换为日期来消除时间。顺便说一句,DateTime是一个数据类型和列的可怕名称。
我不想使用DATEFIRST,因为它不会同等地影响所有日期函数。如果您以后使用带有周数的约会,结果可能是错误的。
我的公司也使用星期一作为本周的开始。通过计算一周中第一天的转移,您可以更改星期日属于哪一周。
CAST(DATEADD( DAY,
(DATEPART( WEEKDAY, [YourDate] ) + 5) % 7 * -1,
[YourDate] )
AS DATE) AS FirstDayOfWeekIsMonday
使用FirstDayOfWeekIsMonday列进行周过滤/分组将确保星期日与之前的星期一相关联。
作为额外的奖励,这个表达式是SARGable,因此仍然可以使用YourDate上的索引。
答案 1 :(得分:0)
分组依据应出现在Order by。
之前您的查询应如下构建:
SET DATEFIRST 1 -- Beginning of week is Monday
SELECT Count(DateTime), ScanPoints, PostPoints
FROM SmartTappScanLog
WHERE DateTime >=
dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND DateTime <
dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
AND UserID = '1' AND BeerID = '3'
GROUP BY DateTime
ORDER BY DateTime ASC
答案 2 :(得分:0)
试一试(未经测试)
SET DATEFIRST 1 -- Beginning of week is Monday
SELECT datepart(dw, DateTime) as Day, ScanPoints, PostPoints, Count(DateTime) as Recs,
FROM SmartTappScanLog
WHERE DateTime >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND DateTime < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
AND UserID = '1' AND BeerID = '3'
GROUP BY datepart(dw, DateTime) , ScanPoints, PostPoints
ORDER BY datepart(dw, DateTime) , ScanPoints, PostPoints