sql >> Database >  >> RDS >> PostgreSQL

Hoe de id te krijgen van de rij die is geselecteerd door de aggregatiefunctie?

Er zijn minstens 3 manieren, zie hieronder:

CREATE TEMP TABLE test (
    id integer, name text, amount numeric, datefrom timestamptz
);

COPY test FROM STDIN (FORMAT csv);
3,a,8,2018-01-01
4,a,3,2018-01-15 10:00
5,b,1,2018-02-20
6,b,1,2019-01-01
\.

Methode 1. met DISTINCT ON (PostgreSQL-specifiek)

SELECT DISTINCT ON (name)
  id, name, amount
FROM test
ORDER BY name, amount DESC, datefrom ASC;

Methode 2. vensterfuncties gebruiken

SELECT id, name, amount FROM (
  SELECT *, row_number() OVER (
    PARTITION BY name
    ORDER BY amount DESC, datefrom ASC) AS __rn
  FROM test) AS x
WHERE x.__rn = 1;

Methode 3. met behulp van co-gerelateerde subquery

SELECT id, name, amount FROM test
WHERE id = (
  SELECT id FROM test AS t2
  WHERE t2.name = test.name
  ORDER BY amount DESC, datefrom ASC
  LIMIT 1
); 


  1. Wat is het verschil tussen MySQL Server en MySQL Client?

  2. Dynamic Select SQL-instructies met MyBatis

  3. Back-up van PostgreSQL met pg_dump en pg_dumpall

  4. MySql-queryanalysator - gratis oplossingen