Postgresql获取具有多列的每个组的最大值

时间:2019-03-24 11:42:33

标签: sql postgresql greatest-n-per-group

我有下表

CREATE table test
(
    random_number INT,
    band VARCHAR(255),
    member_name VARCHAR(255)
);

INSERT INTO test VALUES(2300,'Metallica', 'Kirk');
INSERT INTO test VALUES(2000,'Metallica', 'Lars');
INSERT INTO test VALUES(2500,'Metallica', 'James');
INSERT INTO test VALUES(2800,'Metallica', 'Roberto');
INSERT INTO test VALUES(100,'SkidRow', 'Sebastian');
INSERT INTO test VALUES(140,'SkidRow', 'Rachel');
INSERT INTO test VALUES(110,'SkidRow', 'Scott');
INSERT INTO test VALUES(150,'SkidRow', 'Dave');
INSERT INTO test VALUES(100,'SkidRow', 'Rob');
INSERT INTO test VALUES(500,'Motorhead', 'Lemmy');
INSERT INTO test VALUES(100,'Motorhead', 'Mikkey');
INSERT INTO test VALUES(200,'Motorhead', 'Phil');

我如何获得每个乐队中最大的random_number并返回如下内容:

random_number |   band    | member_name
-----------------------------------------
     2800     | Metallica |  Roberto
     150      | SkidRow   |  Dave
     500      | Motorhead |  Lemmy

3 个答案:

答案 0 :(得分:2)

使用distinct on

select distinct on (band) t.*
from test t
order by band, random_number desc;

Here是db <>小提琴。

distinct on是非常方便的Postgres扩展名。为了提高大型数据集的性能,您需要在(band, random_number desc)上建立索引。

答案 1 :(得分:1)

通过分组并加入表来找到最大的@keyframes

$keyframes-fade: (
  ('left', -100%),
  ('right', 100%)
);

@each $dir, $translateTX in $keyframes-fade {
  @keyframes fade-in-#{$dir} {
    0% {
        opacity: 0;
        transform: translate3d($translateTX, 0, 0);
    }

    100% {
        opacity: 1;
        transform: translate3d(0, 0, 0);
    }
  }
}

请参见demo

答案 2 :(得分:0)

使用MAX()

SELECT max(random_number), band FROM test GROUP BY band

请参阅:https://rextester.com/BEZD44968

结果将是:

no  max band
1   2800 Metallica
2   500 Motorhead
3   150 SkidRow