显示拥有最多FD帐户数量的客户的客户ID和FD帐户数量

问题描述 投票:0回答:2

这里是桌子

account no.  cust_id    Month  Installment  Status
5212340001   1002        30    15000         Closed
5212340002   1002        66    25000         Active
5212340003   1007        36    80555         Closed
5212340004   1003        60    30000         Active

我想找到拥有多个帐户的cust_id的最大出现次数这是我的代码

SELECT CUST_ID,COUNT(CUST_ID) AS C
FROM BANK_FD_ACCOUNT
GROUP BY CUST_ID
HAVING C=MAX(C);

我出错了。但是,预期输出应为:-

cust_id    c
1002       2
mysql sql rdbms
2个回答
1
投票

如果要一行,请使用ORDER BYLIMIT

SELECT CUST_ID, COUNT(CUST_ID) AS C
FROM BANK_FD_ACCOUNT
GROUP BY CUST_ID
ORDER BY C DESC
LIMIT 1;

如果有重复,将返回任意客户。如果要全部使用,请使用RANK()

SELECT c.*
FROM (SELECT CUST_ID, COUNT(*) AS C,
             RANK() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM BANK_FD_ACCOUNT
      GROUP BY CUST_ID
     ) c
WHERE seqnum = 1;

0
投票

@@ GAURAV Sharma您不需要使用HAVING,只需使用ORDER BY语句和LIMIT 1

SELECT CUST_ID,
    COUNT(CUST_ID) AS C
FROM BANK_FD_ACCOUNT
GROUP BY CUST_ID
ORDER BY c DESC 
LIMIT 1;
© www.soinside.com 2019 - 2024. All rights reserved.