gpt4 book ai didi

MySql LEFT JOIN 与 COUNT

转载 作者:行者123 更新时间:2023-11-29 00:30:19 24 4
gpt4 key购买 nike

我有两个表,customers 和 sales。我想计算每个客户的销售额,并为每个商店创建一个每月销售额表。

我想制作类似的东西;

------------------------------
month | customers | sales |
------------------------------
1/2013 | 5 | 2 |
2/2013 | 21 | 9 |
3/2013 | 14 | 4 |
4/2013 | 9 | 3 |

但我在使用以下方法时无法正确计算销售额;

SELECT CONCAT(MONTH(c.added), '/', YEAR(c.added)), count(c.id), count(s.id)
FROM customers c
LEFT JOIN sales s
ON s.customer_id = c.id AND MONTH(c.added) = MONTH(s.added) AND YEAR(c.added) = YEAR(s.added)
WHERE c.store_id = 1
GROUP BY YEAR(c.added), MONTH(c.added);

客户表;

-------------------------------
id | store_id | added |
-------------------------------
1 | 1 |2013-02-01 |
2 | 1 |2013-02-02 |
3 | 1 |2013-03-16 |

销售表;

---------------------------------
id | added | customer_id |
---------------------------------
1 | 2013-02-18 | 3 |
2 | 2013-03-02 | 2 |
3 | 2013-03-16 | 3 |

有人可以帮忙吗?

谢谢

最佳答案

(已更新)现有查询将仅计算添加客户的同一个月的销售额。试试这个,而不是:

SELECT CONCAT(MONTH(sq.added), '/', YEAR(sq.added)) month_year,
sum(sq.customer_count),
sum(sq.sales_count)
FROM (select s.added, 0 customer_count, 1 sales_count
from customers c
JOIN sales s ON s.customer_id = c.id
WHERE c.store_id = 1
union all
select added, 1 customer_count, 0 sales_count
from customers
WHERE store_id = 1) sq
GROUP BY YEAR(sq.added), MONTH(sq.added);

关于MySql LEFT JOIN 与 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16917167/

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