Sql查询以查找列具有最大和的行

Sql查询以查找列具有最大和的行,sql,postgresql,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 20

我有下面的“分数”表,其中有特定年份的球员分数

        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,如何查找相同的内容

我在下面试过了,但它不起作用,因为它不能引用第2 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)

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

或者您也可以使用如下所示的窗口函数行号

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

id  name    score   yr
1   John    500    2016
您还可以与

编辑以获得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

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

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;

我用输出更新了这个问题,问题中的查询结果是拥有最多总分数的玩家,因为这将在您的示例数据中给出拥有最高分数的玩家2016年的合计后ren和john的得分均为500,那么在这种情况下,选择ren@User3580455的逻辑是什么?为什么要使用CTE?一旦引入了窗口函数,就已经解决了这个问题。CTE只是把事情复杂化了。
with cte as (
    select *, 
    DENSE_RANK() OVER(ORDER BY score desc, year) rank 
    from demo 
    where year = 2016
)
select * 
from cte 
where rank = 1
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
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;