I have an mysql statement as below
SELECT CASE
WHEN HOUR(created_at) BETWEEN 0 AND 11 THEN 'Morning'
WHEN HOUR(created_at) BETWEEN 12 AND 15 THEN 'Afternoon'
WHEN HOUR(created_at) BETWEEN 16 AND 18 THEN 'Evening'
WHEN HOUR(created_at) BETWEEN 19 AND 24 THEN 'Night'
END AS session,
SUM(total) AS `total` FROM `orders` WHERE (purchase_date between '2014-05-01' and '2014-05-30')
GROUP BY CASE
WHEN HOUR(created_at) BETWEEN 0 AND 11 THEN 1
WHEN HOUR(created_at) BETWEEN 12 AND 16 THEN 2
WHEN HOUR(created_at) BETWEEN 17 AND 18 THEN 3
WHEN HOUR(created_at) BETWEEN 19 AND 24 THEN 4
END;
I am getting an output like this
+------------+------------+
| session | total |
+------------+------------+
| Morning | 47083.21 |
| Afternoon | 1124804.51 |
| Evening | 165643.34 |
| Night | 1690492.01 |
+------------+------------+
But when there are no entries for morning then the output is missing the Morning row in results but I want an row with morning but total as 0.
please help me how to achieve the same
Expected output
+------------+------------+
| session | total |
+------------+------------+
| Morning | 0 |
| Afternoon | 14804.51 |
| Evening | 16643.34 |
| Night | 19492.01 |
+------------+------------+
actual output is without morning row
Actual output
+------------+------------+
| session | total |
+------------+------------+
| Afternoon | 1124804.51 |
| Evening | 165643.34 |
| Night | 1690492.01 |
+------------+------------+
I would greatly appreciate if Any kind of help or hint is given to solve this problem
解决方案
Add create table cal (hours int not null). Fill it with 0 to 23 (there is no 24 hour?). Then do
SELECT CASE
WHEN cal.hours BETWEEN 0 AND 11 THEN 'Morning'
WHEN cal.hours BETWEEN 12 AND 15 THEN 'Afternoon'
WHEN cal.hours BETWEEN 16 AND 18 THEN 'Evening'
WHEN cal.hours BETWEEN 19 AND 24 THEN 'Night'
END AS session
,sum(coalesce(total, 0)) from
(select created_at, total from orders
where purchase_date between '2014-05-01' and '2014-05-30') T1
right outer join cal on (cal.hours = hour(T1.created_at))
group by CASE
WHEN cal.hours BETWEEN 0 AND 11 THEN 'Morning'
WHEN cal.hours BETWEEN 12 AND 15 THEN 'Afternoon'
WHEN cal.hours BETWEEN 16 AND 18 THEN 'Evening'
WHEN cal.hours BETWEEN 19 AND 24 THEN 'Night' END;