SQL 按日期列分组的一列的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7160315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of one column group by date column
提问by LocustHorde
This should be simple enough but something's gotten me big time.
这应该很简单,但有些事情让我很高兴。
All I have is a table with just TWO columns, something like:
我所拥有的只是一张只有两列的表格,例如:
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
and so on.
等等。
I want to calculate the total word count for each day- I group them by dateadded and select sum of WordCount and finally get the syntax error (wordcount has to be in group by clause) but now I am getting nulls for day's count
我想计算每天的总字数- 我按添加日期对它们进行分组并选择 WordCount 的总和,最后得到语法错误(wordcount 必须在 group by 子句中)但现在我得到了天数的空值
This is my query:
这是我的查询:
select SUM(WordCount) as 'words per day' from @WordsCount group by DateAdded, WordCount
this is selecting just null. How can I know what is wrong?
这是选择空值。我怎么知道出了什么问题?
thanks.
谢谢。
回答by marc_s
What if you use:
如果你使用:
select SUM(WordCount) as 'words per day'
from @WordsCount
group by DateAdded
I don't see why you're also grouping by the word count....
我不明白你为什么还要按字数分组......
Also, since the DateAdded
likely is a DATETIME
column including a time portion, you might want to group by just the date:
此外,由于DateAdded
可能是DATETIME
包含时间部分的列,您可能只想按日期分组:
select SUM(WordCount) as 'words per day'
from @WordsCount
group by CAST(DateAdded AS DATE)
Update:if I try this, the query works just fine ....
更新:如果我尝试这个,查询工作得很好......
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)
and produces the output:
并产生输出:
2008-11-07 128
2008-11-23 25
2008-12-03 62
回答by Daryl Wenman-Bateson
I think this should give you word count per day
我认为这应该给你每天的字数
select SUM(WordCount) as 'words per day' , cast(DateAdded as date) dateAdded
from WordsCount
group by cast(DateAdded as date)