如何查询获得过去七天的总数?

时间:2012-01-09 22:12:19

标签: sql sql-server tsql

我正在使用SQL Server 2008。

我想写一个查询,它给了我一些给定天数的总活动。具体来说,我想计算过去七天每天的总票数。

我的表格如下:

 VoteID --- VoteDate --------------  Vote --- BikeID

 1          2012-01-01 08:24:25      1        1234 
 2          2012-01-01 08:24:25      0        5678
 3          2012-01-02 08:24:25      1        1289
 4          2012-01-03 08:24:25      0        1234
 5          2012-01-04 08:24:25      1        5645
 6          2012-01-05 08:24:25      0        1213
 7          2012-01-06 08:24:25      1        1234
 8          2012-01-07 08:24:25      0        1125

我需要我的结果看起来像这样

VoteDate ---- Total
2012-01-01    5
2012-01-02    6
2012-01-03    7
2012-01-04    1
2012-01-05    3

我的想法是我必须做这样的事情:

SELECT    SUM(CASE WHEN Vote = 1 THEN 1 ELSE 0 END) AS Total
FROM      Votes
GROUP BY  VoteDate

此查询不起作用,因为它只计算同时发生(几乎完全)的投票。当然,我想只关注某一天。我该如何实现这一目标?

2 个答案:

答案 0 :(得分:11)

将其投放为date

SELECT    
     cast(VoteDate as date) as VoteDate, 
     SUM(CASE WHEN Vote = 1 THEN 1 ELSE 0 END) AS Total
FROM      Votes
WHERE VoteDate between dateadd(day, -7, GETDATE()) and GETDATE()
GROUP BY  cast(VoteDate as date)

您的VoteDate列是datetime,但您只需要date部分。最简单的方法是将其转换为date类型。您可以阅读有关SQL Server日期类型here的更多信息。

如果您的Vote列为1或0,则可以执行sum(vote) as Total而不是执行case语句。

答案 1 :(得分:3)

SELECT SUM(Vote) As Total, YEAR(VoteDate),Month(VoteDate),Day(VoteDate)
FROM Votes
Group By YEAR(VoteDate),Month(VoteDate),Day(VoteDate)
可能感兴趣的

Some SQL Server functions

可能感兴趣的

Some MySQL functions