SQL查询找到具有最大总和的行

时间:2018-10-25 05:22:47

标签: sql postgresql

我有下面的“得分”表,其中列出了特定年份的球员得分

        Sid    Name     Score     Year
         1     John     500      2016
         2     Kim      900      2015
         3     Ren      300      2016
         4     John     600      2015
         5     Kim      200      2016     
         6     Ren      200      2016

查找在2016年得分最高的玩家

我可以使用以下查询找到它

Select   Name 
  from
     ( select Name
            , sum(Score) as sumScore 
         from Scores 
       where year=2016 
       group
         by Name
     ) sub 
  order 
    by sumScore desc 
 limit 1;

输出:

如何在不使用order by的情况下找到相同的商品?

我在下面尝试过,但由于无法在第二个where子句中引用sub并抱怨关系sub不存在而无法正常工作

select Name from(select Name,sum(Score) as sumScore from Scores 
where year=2016 group by Name)sub where sumScore=(select max(sumScore) from sub)

4 个答案:

答案 0 :(得分:1)

一种简单的方法使用窗口函数:

select s.*
from (select s.*, max(s.score) over (partition by year) as max_score
      from scores s
      where year = 2016
     ) s
where score = max_score;

答案 1 :(得分:0)

您可以尝试使用相关子查询

DEMO

p.dropify-infos-message

或者您可以使用如下所示的窗口函数row_number()

select * from tablename a where score in 
(select max(score) from tablename b where a.year=b.year and b.year=2016)
and a.year=2016

输出:

select * from 
(
select *,row_number() over(partition by yr order by score desc) as rn from cte1 
)a where rn=1 and yr=2016

答案 2 :(得分:0)

SELECT Scores.Name, SUM(Scores.Score)
FROM (
      select Name,sum(Score) as sumScore, Years 
      from Scores 
      where Years=2016 
      group by Name, Years
     )sub INNER JOIN Scores ON sub.Name = Scores.Name
GROUP BY Scores.Name
HAVING SUM(Scores.Score) = MAX(sub.sumScore)

答案 3 :(得分:0)

您也可以将common table expressiondense rank组合使用

with cte as (
    select *, 
    DENSE_RANK() OVER(ORDER BY score desc, year) rank 
    from demo 
    where year = 2016
)
select * 
from cte 
where rank = 1

Demo

编辑以获取最高分数为2016的玩家,您可以将上述查询调整为

with cte as (
    select name,year ,
    DENSE_RANK() OVER(ORDER BY sum(score) desc, year) rank 
    from demo 
    where year = 2016
    group by name,year
)
select * 
from cte 
where rank = 1

Demo