I have a some tables that I am storing records in
transactions --- | id | type_id | value | created_at | |----|---------|-------|---------------------| | 1 | 3 | 10 | 2016-11-01 09:00:00 | | 2 | 3 | 15 | 2016-11-01 10:00:00 | | 3 | 3 | 10 | 2016-11-03 09:00:00 | types --- | id | name | |----|--------| | 3 | 'Type' |
What I want to get is the total (sum) of the transaction values per day since the beginning of time, with days with no records showing as 0:
results --- | type | total | date | |------|-------|------------| | Type | 25 | 2016-11-01 | | Type | 0 | 2016-11-02 | | Type | 10 | 2016-11-03 |
I can do this pretty easily when only being interested in the results that have values but query doesn't return dates with no records:
SELECT `types`.`name` as `type`, SUM(`transactions`.`value`) as `total`, DATE_FORMAT(`transactions`.`created_at`) as `date` FROM `transactions` JOIN `types` ON `transactions`.`type_id` = `types`.`id` GROUP BY `date`, `types`.`id`
Unfortunately, I need to get all dates between a range and return the values, defaulting to zero. the range could be variable depending on what the user selects.