Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of one column group by date column

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

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.

like image 817
LocustHorde Avatar asked Aug 23 '11 11:08

LocustHorde


People also ask

Can we use SUM with GROUP BY?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group.

How do I SUM a date in a column in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

Can you GROUP BY date in SQL?

To group by date part, use the GROUP BY clause and the EXTRACT() function. Pass EXTRACT() the date parts to isolate.

Can we use count with GROUP BY clause?

The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.


1 Answers

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:

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
like image 175
marc_s Avatar answered Sep 27 '22 23:09

marc_s