SQL - 替代方案

时间:2015-04-14 07:57:36

标签: sql

以下查询为我提供了计数值列表:

SELECT books.name as a, 
COUNT(library.staff)as b
FROM library, books  
WHERE library.staff = books.id
GROUP BY books.name;

如何获得输出的最大值

2 个答案:

答案 0 :(得分:1)

您可以使用window functions吗?

SELECT a, b
  FROM (
    SELECT books.name as a, 
           count(library.staff) as b
           row_number() OVER (ORDER BY count(library.staff) DESC) as rn
      FROM library, books  
     WHERE library.staff = books.id
     GROUP BY books.name
    ) s
 WHERE rn=1;

答案 1 :(得分:1)

没有窗口功能或限制:

with data as (
  select books.name as a, 
         COUNT(library.staff) as b
  FROM library
    JOIN books ON library.staff = books.id
  GROUP BY books.name
) 
select *
from data
where b = (select max(b) from data);

但也许你现在要添加另一个要求,说明“没有常用的表格表达式”:

select books.name as a, 
       count(library.staff) as b
from library l
  join books b on l.staff = b.id
group by b.name
having count(l.staff) = (select max(cnt) 
                         from (
                            select count(*) cnt
                            from library l
                              join books b on l.staff = b.id
                            group by b.name) t 
                         );

如果books.id是主要(或唯一)键,则可以使用以下方式稍微简化第二个语句:

select l.name as a, 
       count(l.staff) as b
from library l
  join books ON l.staff = b.id
group by b.name
having count(l.staff) = (select max(cnt) 
                         from (
                             select count(*) cnt
                             from library l
                             group by l.staff) t 
                         );
相关问题