gpt4 book ai didi

如果用 group by 子句找不到记录,MySQL 返回 0 作为值

转载 作者:行者123 更新时间:2023-11-30 22:23:34 25 4
gpt4 key购买 nike

我想按月获取所有客户订单,我成功获得了查询,但如果任何客户在任何月份没有订单,我需要 0 或 null。

例如:

+--------------+----------------+-------------+
| date | customer | order |
+--------------+----------------+-------------+
| january 2016 | abc | 2345 |
| Febuary 2016 | abc | 2234 |
| january 2016 | xyz | 2345 |
| febuary 2016 | xyz | 0/null |
+--------------+----------------+-------------+

但我的 sql 查询返回类似这样的内容

+--------------+----------------+-------------+
| date | customer | order |
+--------------+----------------+-------------+
| january 2016 | abc | 2345 |
| Febuary 2016 | abc | 2234 |
| january 2016 | xyz | 2345 |
+--------------+----------------+-------------+

我的查询

SELECT 
CONCAT(so.month, ' ', so.year) months,
c.customer_name,
so.qty
FROM
customer c
JOIN
(
SELECT
o.customer_id,
MONTHNAME(o.date) MONTH,
YEAR(o.date) YEAR,
SUM(o.quantity) qty
FROM
sale_order o
WHERE
o.order_type = 'kg'
AND
o.date BETWEEN '2015-01-01' AND '2016-01-01'
GROUP BY YEAR(o.date), MONTHNAME(o.date), o.customer_id
) so
on so.customer_id = c.customer_id

最佳答案

您可以选择月份和年份的所有不同值,然后左连接到您的其余结果,如下所示:

SELECT 
CONCAT(t.month, ' ', t.year) months,
c.customer_name,
so.qty
FROM (select distinct MONTHNAME(date) as month,year(date) as year from sale_order
where date BETWEEN '2015-01-01' AND '2016-01-01') t
INNER JOIN customer c
ON(1=1)
LEFT OUTER JOIN
(
SELECT
o.customer_id,
MONTHNAME(o.date) MONTH,
YEAR(o.date) YEAR,
SUM(o.quantity) qty
FROM
sale_order o
WHERE
o.order_type = 'kg'
AND
o.date BETWEEN '2015-01-01' AND '2016-01-01'
GROUP BY YEAR(o.date), MONTHNAME(o.date), o.customer_id
) so
on (so.customer_id = c.customer_id and
so.year = t.year and
so.month = t.month)

关于如果用 group by 子句找不到记录,MySQL 返回 0 作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36005575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com