我试图在多个表中进行计数(*),但是将它们放在一个组中。
我在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相同 - 她只是table2中的客户,而不是table1或table 3等。
答案 0 :(得分:2)
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
答案 1 :(得分:0)
请在联盟之前使用()
像
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