簡體   English   中英

Sql 查詢以根據條件獲取不同的行

[英]Sql query to get distinct rows based on a criteria

我想根據分數確定 SQL 以獲得每個年級的第一名

scores:
+----+---------+--------+
| id | score   | grade  |
+----+---------+--------+
|  1 |  48     |  1     |
|  2 |  56     |  2     |
|  3 |  69     |  1     |
|  4 |  35     |  1     |
|  5 |  78     |  2     |
|  6 |  90     |  2     |
|  7 |  87     |  2     |
|  8 |  33     |  1     |
+----+---------+--------+

Expeted Result:
+----+---------+--------+
| id | score   | grade  |
+----+---------+--------+
|  3 |  69     |  1     |
|  6 |  90     |  2     |
+----+---------+--------+

我現在正在做的是:

   allGrades = [1, 2]
   for <grade> in allGrades:
       select * from scores where grade=<grade> order by score desc limit 1;

有沒有更有效的方法在單個查詢中執行此操作?

我正在嘗試使用帶有 postgres 的 sqlalchemty 來做到這一點 - 但 SQL 解決方案會很好,我可以轉換它。

select s.* 
from scores s
inner join (
select grade, max(score) as score 
from scores
group by grade ) sg on s.grade = sg.grade and s.score = sg.score;

DBFiddle 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM