MySQL:为什么查询因SUM而给出NULL?

时间:2014-12-30 14:18:20

标签: mysql null

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来自哪里?
B.我怎么能避免它?

1 个答案:

答案 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' - 但只有一个值。以上应该解决问题。