Forum Moderators: open

Message Too Old, No Replies

Help with grouped query

         

Andy Langton

6:30 pm on Jan 31, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a database that can be simplified as below:

+------------+---------+----------+
| Date | Clicks | Category |
+------------+---------+----------+
| 2019-10-24 | 100 | Widgets |
| 2019-10-24 | 200 | Widgets |
| 2019-10-24 | 300 | Gadgets |
| 2019-11-24 | 250 | Widgets |
| 2019-11-24 | 200 | Widgets |
| 2019-11-24 | 100 | |
| 2019-11-24 | 200 | Gadgets |
| 2019-12-24 | 100 | Widgets |


What I want to do is group by both date and category (so I can plot the sum of clicks for the category over time). I've tried the below:


SELECT `Date`, `department`, SUM(`Clicks`) FROM `Category` WHERE `Category`<>'' GROUP BY `Category` , `Date`


Unfortunately, this doesn't work and I'm exhausting my rather lacking knowledge of SQL. From my example table above, I'm trying to get output like the below:


+------------+--------+----------+
| Date | Clicks | Category |
+------------+--------+----------+
| 2019-10-24 | 300 | Widgets |
| 2019-10-24 | 300 | Gadgets |
| 2019-11-24 | 450 | Widgets |
| 2019-12-24 | 200 | Gadgets |
| 2019-12-24 | 100 | Widgets |
+------------+--------+----------+


I.e. the sum of clicks for a given date grouped by category. If this is potentially a database design issue, I have the opportunity to change the database structure. Appreciate any help!

topr8

8:27 pm on Jan 31, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



i'm not sure if you've transposed/anonymised this correctly (you seem to have swapped over departments and categories - one is a field the other a table name i assume)... but do you mean...

SELECT `date`, SUM(clicks) as clicks, Category from tablename
WHERE Category <> ''
GROUP BY `Date`,Category;

... if you can change things thendon't name columns with reserved words: date

Andy Langton

2:00 pm on Feb 1, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks! Yes, you're right I didn't quite "generalise" the example correctly.

if you can change things then don't name columns with reserved words: date


Thanks again - it isn't actually named "date" - I just used that for my example.

Your suggestion works great, by the way. I think my original code was very close and I assumed this was more complicated than I thought!

topr8

7:59 pm on Feb 1, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



you're welcome - although you'd pretty much done it yourelf already!