sql - 如何在mysql中查找每个客户的type1和type2的交易计数

标签 sql mysql pivot-table

我有一个客户表:

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/

相关文章:

java - : sequence id using JPA @TableGenerator, @GeneratedValue 与数据库 Auto_Increment 之间有什么区别

mysql - 创建 VIEW 但更改所选列的数据类型

mysql - 带有内部连接的 SQL 更新查询给出了超过锁定等待超时

mysql - 为什么我不应该为 max_connections 使用最大值

MySQL,同时在内部和外部查询中进行分组

删除文件DSN后Excel查询表仍然有效,怎么可能?

python - django: select_related() 在一个已经存在的对象上?

mysql - SQL 查询错误 - 从带条件的表中选择

excel - 枢轴平面 View

database - 如何在 Excel 中使用带有查询的 Access 数据库作为数据透视表