只选择一个在sql中具有最高计数的行

时间:2015-06-18 18:26:06

标签: sql oracle select

我只需要选择一行中计数最多的一行。我怎么做?

这是我目前的代码:

 select firstname, lastname, count(*) as total
 from trans 
 join work 
 on trans.workid = work.workid
 join artist
 on work.artistid = artist.artistid
 where datesold is not null
 group by firstname, lastname;

当前示例:

FIRSTNAME |  LASTNAME |  TOTAL
------------------------------
Tom       |   Cruise  |   3
Angelina  |   Jolie   |   9
Britney   |   Spears  |   5
Ellie     |  Goulding |   4

我需要它才能选择这个:

FIRSTNAME  |  LASTNAME  |  TOTAL
--------------------------------
Angelina   |  Jolie     |   9

4 个答案:

答案 0 :(得分:1)

您可以添加order by total descfetch first 1 row only仅限Oracle 12c r1 ,否则您应该将结果用作临时表并使用select来使用rownum = 1子句中的where限制,以防您total对于不同的组不能相同。另一种方法是添加此having子句,以便列出所有人员total的最大值:

having count(*) = (select max(total) from (select count(*) as total from <your_query>) tmp)

或那:

having count(*) = (select count(*) as total from <your_query> order by total desc fetch first 1 row only)

答案 1 :(得分:0)

在Oracle 12中,您可以这样做:

 select firstname, lastname, count(*) as total
 from trans join
      work 
      on trans.workid = work.workid join
      artist
      on work.artistid = artist.artistid
 where datesold is not null
 group by firstname, lastname
 order by count(*) desc
 fetch first 1 row only;

在旧版本中,您可以使用子查询执行此操作:

select twa.*
from (select firstname, lastname, count(*) as total
      from trans join
           work 
           on trans.workid = work.workid join
           artist
           on work.artistid = artist.artistid
      where datesold is not null
      group by firstname, lastname
      order by count(*) desc
     ) twa
where rownum = 1;

答案 2 :(得分:0)

这将适用于sql server 2012 ..

&#13;
&#13;
with CTECount (firstname, lastname,total)
as
(
	select firstname, lastname, count(1) as total
	 from trans 
	 join work 
	 on trans.workid = work.workid
	 join artist
	 on work.artistid = artist.artistid
	 where datesold is not null
	 group by firstname, lastname
 )

 select top(1) with ties from CTECount 
 order by total desc
&#13;
&#13;
&#13;

由于

答案 3 :(得分:0)

你可以这样做,非常简单:

选择 TOP 1 firstname,lastname,count(*)作为trans的总数 加入trans.workid = work.workid的工作 在work.artistid = artist.artistid上加入艺术家 其中dateold不为null 按名字,姓氏分组 按总DESC排序;