mysql case 不做处理,当内部mysql case语句未显示在结果中时不匹配

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值