选择具有最大值的行的最佳方法是什么?

时间:2014-04-16 17:53:23

标签: mysql sql greatest-n-per-group

我遇到了一个任务,我设法完成了目标,但我得到的解决方案不是最佳的,我需要更优化的解决方案。我使用普通的子查询可能是相关的子查询可以更好地解决这个问题。

这是我制作的表格

SELECT custid, 
       count(DISTINCT bid) AS Total 
FROM   loan 
GROUP  BY custid; 

这个输出如下: -

enter image description here

我想要的是具有最大总数的custid

一种方法是使用Order by Total DESC LIMIT 1,但这只会产生1个结果。

我做的是

SELECT custid 
FROM   (SELECT custid, 
               count(DISTINCT bid) AS Total 
        FROM   loan 
        GROUP  BY custid) c1 
WHERE  total = (SELECT max(Total) 
                FROM   (SELECT custid, 
                               count(DISTINCT bid) AS Total 
                        FROM   loan 
                        GROUP  BY custid) c2) 

这给了我正确的结果

enter image description here

我想要做的是减少代码,因为在这里我再次写同样的东西。我知道必须有一个更简单的方法来做到这一点。也许是相关的查询。

寻找一些好的答案。这基本上只是为了清除我的概念

抱歉,如果是noob问题。我是SQL的小伙伴。

3 个答案:

答案 0 :(得分:2)

通过@Ravinder的提示了解OP想要的内容,
我想你需要构建mysql函数GROUP_CONCAT,sql是:

select custid_count.Total, GROUP_CONCAT(custid_count.custid order by custid_count.custid asc SEPARATOR ',') as custids from
(select custid, count(distinct bid) as Total from loan group by custid order by Total desc) as custid_count
group by custid_count.Total
order by custid_count.Total desc
limit 1;

结果列custids是由','结合的最大ID,在查询之后,你需要用','分割custids并将每个子字符串转换为你需要的数字类型,

答案 1 :(得分:0)

这是另一种方式:

select * from loan
where custid = 
(
    select custid_count.custid from
    (select custid, count(distinct bid) as Total from loan group by custid order by Total desc) as custid_count
    order by custid_count.Total desc
    limit 1

);

首先找到最大计数的custid,然后查询与custid匹配的所有行,

答案 2 :(得分:0)

我还没有在mysql中尝试过这个,但是在sql语言中,我使用它可以很好地使用没有组的聚合函数,所以这样的事情

select custid, total, max(total) as maxtotal
from (select custid, count(distinct bid) as total
      from loan
      group by custid) c1;

会在每一行上标记单个客户总数和表格最大总数,并且您只需要对总数等于最大总数的那些进行过滤。这会给你一个类似的结论:

select custid
from (select custid, count(distinct bid) as total
from loan
group by custid) c1
where total = max(total);
相关问题