简体   繁体   English

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

[英]Sql query to find the row having max sum for a column

I have following 'Scores' table which has score of players in a specific year 我有一个“分数”表,其中有特定年份的球员分数

        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

Find the player who has scored maximum runs in 2016 查找在2016年得分最高的玩家

I can find this using the below query 我可以使用以下查询找到它

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

Ouput: Ren Ouput:

How can i find the same without using order by? 如何在不使用order by的情况下找到相同的商品?

I tried below but it doesn't work as it can't refer sub in 2nd where clause and complains relation sub doesn't exist 我在下面尝试过,但由于无法在第二个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)

One simple method uses window functions: 一种简单的方法使用窗口函数:

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;

You can try using correlated subquery 您可以尝试使用相关子查询

DEMO DEMO

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

OR you can use window function row_number() like below 或者您可以使用如下所示的窗口函数row_number()

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

OUTPUT: OUTPUT:

id  name    score   yr
1   John    500    2016
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)

You could also use common table expression in combination with dense 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 演示

Edit to get players with max score of 2016 you can tweak above query as 编辑以获取最高得分为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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM