没有时间戳的每日记录数

时间:2015-06-18 05:49:15

标签: sql-server tsql

我正在尝试查询我们每天收到的报价数量,与过去14天相比。

我尝试的第一个查询是:

SELECT CreatedDateTime, count(CreatedDateTime)
FROM dbo.Quotes
WHERE CreatedDateTime >= dateadd(day, datediff(day,0,GetDate())- 14,0)
GROUP BY CreatedDateTime
ORDER BY CreatedDateTime DESC

但是我认为数据的时间戳会单独计算每条记录,而不是每天对记录进行分组。我该如何修改此查询?

我尝试了以下操作,但在关键字' FROM'附近的语法不正确。

SELECT convert(char(10), dbo.Quotes.CreatedDateTime, count (CreatedDateTime)
FROM dbo.Quotes
WHERE CreatedDateTime >= dateadd(day, datediff(day,0,GetDate())- 14,0)
GROUP BY convert(char(10), dbo.Quotes.CreatedDateTime
ORDER BY CreatedDateTime DESC

2 个答案:

答案 0 :(得分:1)

是的,因为您按日期和时间进行分组,您需要按时间分组。

只需将group子句修改为此

即可
  GROUP BY DATE_FORMAT(CreatedDateTime , '%Y-%m-%d') 

所以你的查询看起来像是

SELECT CreatedDateTime, count(*) as totalQuotes
FROM dbo.Quotes
WHERE CreatedDateTime >= dateadd(day, datediff(day,0,GetDate())- 14,0)
GROUP BY DATE_FORMAT(CreatedDateTime , '%Y-%m-%d') 
ORDER BY DATE_FORMAT(CreatedDateTime , '%Y-%m-%d') DESC

答案 1 :(得分:1)

您正在计算用于GROUP BY的相同列 当然,每组只有一个值。 尝试使用COUNT(*)代替 另外,要忽略时间部分,最简单的事情就是强制转换(假设您的数据库版本是2008或更高版本)

SELECT CAST(CreatedDateTime as Date), count(*)
FROM dbo.Quotes
WHERE CreatedDateTime >= dateadd(day, datediff(day,0,GetDate())- 14,0)
GROUP BY CAST(CreatedDateTime as Date)
ORDER BY CAST(CreatedDateTime as Date) DESC