按日期列的一列组的总和

时间:2011-08-23 11:31:17

标签: sql tsql sql-server-2008

这应该很简单,但有些东西让我很开心。

我只有一张只有两列的表格,如:

 WordCount          DateAdded
 `````````````````````````````
 96                 2008-11-07 09:16:31.810
 32                 2008-11-07 15:26:27.547
 25                 2008-11-23 16:05:39.640
 62                 2008-12-03 12:33:03.110

等等。

我想计算每天的总字数 - 我按照dateadded对它们进行分组并选择WordCount的总和,最后得到语法错误(wordcount必须在group by子句中)但是现在我得到的是一天数的空白

这是我的疑问:

select SUM(WordCount) as 'words per day' from @WordsCount group by DateAdded, WordCount

这只是选择null。我怎么知道什么是错的?

感谢。

2 个答案:

答案 0 :(得分:9)

如果您使用以下内容:

select SUM(WordCount) as 'words per day' 
from @WordsCount 
group by DateAdded

我不明白你为什么还要用字数来分组......

此外,由于DateAdded可能是包含时间部分的DATETIME列,因此您可能只想按日期进行分组:

select SUM(WordCount) as 'words per day' 
from @WordsCount 
group by CAST(DateAdded AS DATE)

更新:如果我试试这个,查询就可以了....

DECLARE @WordsCnt TABLE (WordCount INT, DateAdded DATETIME)

INSERT INTO @wordsCnt(WordCount, DateAdded)
VALUES(96, '2008-11-07 09:16:31.810'),
      (32, '2008-11-07 15:26:27.547'),
      (25, '2008-11-23 16:05:39.640'),
      (62, '2008-12-03 12:33:03.110')

select CAST(DateAdded AS DATE), SUM(WordCount) as 'words per day' 
from @WordsCnt
group by CAST(DateAdded AS DATE)

并生成输出:

2008-11-07   128
2008-11-23    25
2008-12-03    62

答案 1 :(得分:6)

我认为这应该给你每天的字数

select      SUM(WordCount) as 'words per day' , cast(DateAdded as date) dateAdded
from        WordsCount 
group by    cast(DateAdded as date)