SQL Customer 和 Transaction 中有 2 个表,显示已完成最大交易数的客户详细信息

There are 2 tables in SQL Customer and Transaction, Display the customer details who has done maximum number of transactions

以下是 table 属性:

  1. 客户Table:客户 ID、客户姓名、地址、电子邮件 ID 和手机号码。
  2. 交易Table:交易ID、交易类型、金额和客户ID。

您可以使用计算其交易次数的聚合查询加入客户 table:

select c.*, t.cnt
from customers c
inner join (select customerid, count(*) cnt from transactions group by customerid) t
    on t.customerid = c.customerid
order by t.cnt desc
limit 1

如果不需要在结果集中显示事务计数,也可以使用关联子查询进行过滤:

select c.*
from customers c
order by (select count(*) from transactions t where t.customerid = c.customerid) desc
limit 1

如果你想允许顶级关系,那么一种选择是使用 window 函数(仅在 MySQL 8.0 中可用):

select c.*
from customers c
inner join (
    select customerid, count(*) cnt, rank() over(order by count(*) desc) rn
    from transactions 
    group by customerid
) t on t.customerid = c.customerid
where t.rn = 1
DECLARE @number_of_transactions INT = --(YOUR DESIRED MAXIMUM NUMBER OF TRANSACTION)
SELECT * FROM customer_table a INNER JOIN transaction_table b ON a.customer_id = b.customer_id WHERE COUNT(b.transaction_id) = @number_of_transactions
ORDER BY customer_id;