表orders
中的列如下:
order_id, order_nr, created_at, order_value, payment_method
我希望按月对2014年的订单进行分组,并根据付款方式检查其值的总和。
我得到了一个问题:
SELECT
month(created_at),
CASE WHEN payment_method = 'Cash' THEN sum(order_value) END as Cash,
CASE WHEN payment_method = 'CreditCard' THEN sum(order_value) END as CreditCard
FROM orders
WHERE month(created_at) BETWEEN 5 AND 6
AND year(created_at) = 2014
GROUP BY month(created_at)
ORDER BY order_value
问题:对于CreditCard,结果为空。
我做了什么:
- 我检查了order_value为空的订单是否为空 - 我没有找到任何订单
- 我试过COALESCE(sum(order_value),0)
- 我试过sum(IFNULL(order_value,0))
- 我使用了这个查询:
SELECT
month(created_at) as m,
CASE WHEN payment_method = 'CreditCard' THEN sum(order_value) END as CreditCard
FROM orders
AND month(created_at) BETWEEN 5 AND 6
AND year(created_at) = 2014
GROUP BY month(created_at), payment_method /*here is the difference*/
ORDER BY month(created_at) ASC
给我的结果如下:
m | CreditCard
---------------
5 | NULL
5 | NULL
5 | 13256
6 | NULL
6 | NULL
6 | 15356
你可以向我解释一下
答:null来自哪里? 答案 0 :(得分:3)
我很确定你想要条件聚合 - case
语句里面 sum()
:
SELECT month(created_at),
SUM(CASE WHEN payment_method = 'Cash' THEN order_value END) as Cash,
SUM(CASE WHEN payment_method = 'CreditCard' THEN order_value END) as CreditCard
FROM orders
WHERE month(created_at) BETWEEN 5 AND 6 AND year(created_at) = 2014
GROUP BY month(created_at)
ORDER BY SUM(order_value);
如果您想要0
而非NULL
,则可以在ELSE 0
条款中添加WHERE
。
您的查询存在的问题是SELECT
中的列不在GROUP BY
中。这些值来自 indeterminate 匹配行。该行payment_method
的值为'Cash'
或'Credit'
- 但只有一个值。以上应该解决问题。