如何在SQL中使用GROUP BY DATETIME列

时间:2017-10-04 10:29:24

标签: sql sql-server

我有一张表可以跟踪用户扫描徽标的时间。它跟踪扫描的DATETIME以及扫描用户的分数(1到5之间)

我正在尝试计算给定周的每天平均分数。我遇到的挑战是当我使用GROUP BY时,我每次扫描都会回来,因为DATETIME值是第二个无法分组的。

SET DATEFIRST 1 -- Beginning of week is Monday
SELECT SUM(Points) AS Points, DateTime
FROM SmartTappScanLog
WHERE DateTime >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) 
  AND DateTime <  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
GROUP BY DATETIME

我尝试过几件事情,包括:

GROUP BY CAST(DATETIME As DATE)

1 个答案:

答案 0 :(得分:1)

您可以使用DATEPART(),例如:

SELECT SUM(Points) AS Points, MIN(DateTime) as  DateTime
FROM SmartTappScanLog
WHERE DateTime >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) 
  AND DateTime <  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
GROUP BY DATEPART(day,DATETIME)