我有一个客户表:
id name
1 customer1
2 customer2
3 customer3
和交易表:
id customer amount type
1 1 10 type1
2 1 15 type1
3 1 15 type2
4 2 60 type2
5 3 23 type1
我希望查询返回的是下表
name type1 type2
customer1 2 1
customer2 0 1
customer3 1 0
这表明 customer1 已进行两笔类型 1 的交易和 1 笔类型 2 的交易,依此类推。
是否有一个查询可以用来获取此结果,或者我是否必须使用程序代码。
最佳答案
你可以试试
select c.id as customer_id
, c.name as customer_name
, sum(case when t.`type` = 'type1' then 1 else 0 end) as count_of_type1
, sum(case when t.`type` = 'type2' then 1 else 0 end) as count_of_type2
from customer c
left join `transaction` t
on c.id = t.customer
group by c.id, c.name
此查询只需在连接上迭代一次。
关于sql - 如何在mysql中查找每个客户的type1和type2的交易计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1465160/