Let’s say I have the following table:
id | letter | date
--------------------------------
1 | A | 2011-01-01
2 | A | 2011-04-01
3 | A | 2011-04-01
4 | B | 2011-01-01
5 | B | 2011-01-01
6 | B | 2011-01-01
I would like to make a count of the rows broken down by letter and date, and sum the count of all the previous dates. every letter should have a row to every date of the table (ie. letter B doesn’t have a 2011-04-01 date, but still appears in the result)
The resulting table would look like this
letter| date | total
--------------------------------
A | 2011-01-01 | 1
A | 2011-04-01 | 3
B | 2011-01-01 | 3
B | 2011-04-01 | 3
How to achieve this in a SQL query?
Thank you for your help!
NOTE
I didn’t notice it was mysql, which doesn’t support CTE. You may be able to define temporary tables to use this.
This is an interesting problem. You kind of need to join all letters with all dates and then count the preceding rows. If you weren’t concerned with having rows for letters that have a count of 0 for the dates, you could probably just do something like this:
/deleted CTE solution/
Solution without CTE