Return 每组具有最大值的行

Return the row with max value for each group

我有以下 table 名称 t2:

  realm   |    race    | gender | total  
----------+------------+--------+--------
 Buffalo  | faerie     | F      |   5972
 Buffalo  | faerie     | M      |   2428
 Buffalo  | footballer | F      |   1954
 Buffalo  | footballer | M      |   2093
 Buffalo  | raccoon    | F      |   2118
 Buffalo  | raccoon    | M      |   1237
 Buffalo  | shark      | F      |  12497
 Buffalo  | shark      | M      |   3621
 Buffalo  | wizard     | F      |    468
 Buffalo  | wizard     | M      |  11079
 Camelot  | faerie     | F      |   2414
 Camelot  | faerie     | M      |   1455

我想创建一个只选择总计最高的领域、种族和性别的查询。每次我使用 GROUP BY 我都会得到两种性别。

输出 table 如下所示:

  realm   |    race    | gender | total  
----------+------------+--------+--------
 Buffalo  | faerie     | F      |   5972
 Buffalo  | footballer | M      |   2093
 Buffalo  | raccoon    | F      |   2118
...

我想我对如何比较行的理解很差。
我不知道如何编写 WHERE 子句,这样当我 GROUP BY realm,race,gender 时,我只能得到 1 个性别。

DISTINCT ON 的完美用例:

SELECT DISTINCT ON (realm, race) *
FROM   tbl
ORDER  BY realm, race, total DESC;

db<>fiddle here

值得注意的是,查询根本没有 GROUP BY
假设总数为 NOT NULL,否则追加 NULLS LAST.
在平局的情况下,获胜者是任意的,除非您添加更多 ORDER BY 项来打破平局。

详细解释:

  • Select first row in each GROUP BY group?
select q.realm
, q.race
, q.gender
, q.total

from (
    Select t2.realm
    , t2.race
    , t2.gender
    , total
    , max(total) over (partition by t2.realm, t2.race) as maxtotal

    FROM adventure t2
) q
where q.total = q.maxtotal