MySQL - 按空值分组

时间:2016-04-29 10:00:32

标签: mysql sql

我有以下SQL查询:

SELECT date_format(sfo.shipping_arrival_date,"%m.%Y") AS Month,
       date_format(sfo.shipping_arrival_date,"%v") AS Week,
       date_format(sfo.shipping_arrival_date,"%d.%m.%Y") AS Shipping Day,
       CASE
           WHEN sfo.coupon_code IS NOT NULL THEN sfo.coupon_code
           ELSE 'no Code'
       END as Coupon,
       sfo.coupon_rule_name,
       sfo.grand_total AS Endsumme,
       sfo.base_subtotal + sfo.shipping_incl_tax AS Sum_Incl_Shipping,
       sfo.discount_amount,
       count(sfo.entity_id) AS uses
FROM sales_flat_order AS sfo
WHERE sfo.status <> 'canceled'
GROUP BY Coupon
ORDER BY sfo.shipping_arrival_date DESC

在sfo.coupon_code中是值&#34; NULL&#34;现有的,但查询不会将它们列为&#34;没有代码&#34;在结果中。我想要一份分组的优惠券代码和相关值的列表。

有谁知道为什么我找不到价值&#34;没有代码&#34;在我的结果?

感谢。

2 个答案:

答案 0 :(得分:0)

我的预感是NULL的{​​{1}}值只有coupon_codesfo.status = NULL的记录会从结果集中省略。

尝试使用以下查询:

SELECT date_format(sfo.shipping_arrival_date,"%m.%Y") AS Month,
       date_format(sfo.shipping_arrival_date,"%v") AS Week,
       date_format(sfo.shipping_arrival_date,"%d.%m.%Y") AS Shipping Day,
       CASE
           WHEN sfo.coupon_code IS NOT NULL THEN sfo.coupon_code
           ELSE 'no Code'
       END as Coupon,
       sfo.coupon_rule_name,
       sfo.grand_total AS Endsumme,
       sfo.base_subtotal + sfo.shipping_incl_tax AS Sum_Incl_Shipping,
       sfo.discount_amount,
       count(sfo.entity_id) AS uses
FROM sales_flat_order AS sfo
WHERE sfo.status <> 'canceled' OR sfo.status IS NULL
GROUP BY Coupon
ORDER BY sfo.shipping_arrival_date DESC

答案 1 :(得分:0)

我使用COALESCE代替CASE ......

customerContracts

...因为COALESCE表达式是CASE表达式的语法快捷方式,因此更清晰简洁