gpt4 book ai didi

mysql - group by count(*) mysql 多个表

转载 作者:行者123 更新时间:2023-11-29 08:05:34 24 4
gpt4 key购买 nike

我正在尝试跨多个表进行计数(*),但将它们放在一个组中。

我在 mysql 中的查询是:

SELECT
(SELECT COUNT(*) as 'Orders', Customer FROM table WHERE `date` = CURRENT_DATE()) as Client1,
(SELECT COUNT(*) as 'Orders', Customer FROM table2 WHERE `date` = CURRENT_DATE()) as Client2,
(SELECT COUNT(*) as 'Orders', Customer FROM table3 WHERE `date` = CURRENT_DATE()) as Client3
group by Customer

这就是我想要找回的:

+-------------+---------+---------+---------+
| Customer | Client1 | Client2 | Client3 |
+-------------+---------+---------+---------+
| John Doe | 88 | 19 | 0 |
+-------------+---------+---------+---------+
| Mary P | 0 | 32 | 0 |
+-------------+---------+---------+---------+
| Scott K | 11 | 25 | 31 |
+-------------+---------+---------+---------+

我唯一担心的是客户不会存在于其他表中,例如 - John Doe 仅是 table1 中的客户 - 而不是 table2 或 table3 中的客户。

与 Mary P 相同 - 她只是表 2 中的客户,而不是表 1 或表 3 等中的客户。

最佳答案

select a.Customer, sum(client1), sum(client2), sum(client3)
from
(
select Customer, count(*) as client1, 0 as client2, 0 as client3 from table WHERE `date` = CURRENT_DATE() group by Customer
union all
select Customer, 0, count(*), 0 from table2 WHERE `date` = CURRENT_DATE() group by Customer
union all
select Customer, 0, 0, count(*) from table3 WHERE `date` = CURRENT_DATE() group by Customer
) as a
group by a.Customer

关于mysql - group by count(*) mysql 多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778940/

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