D
D
dozzzzer2020-10-29 23:09:35
PostgreSQL
dozzzzer, 2020-10-29 23:09:35

Grouping in PostgreSQL?

There is a table:

id| country | salary
1 | sweden | 3000
2 | germany| 3900
3 | sweden | 3500
4 | sweden | 29005
| germany| 3300

Required:

  1. get records with maximum salary values ​​in each of the countries
  2. get the id of those posts


Expected result:
id | country | salary
3 | sweden | 3500
2 | germany| 3900

Which query to use to achieve this result?

query: returns error: column "t.id" must appear in a GROUP BY clause or be used in an aggregate function
SELECT id, max(salary) FROM t GROUP BY country;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2020-10-29
@dozzzzer

SELECT t.id, t.country, t.salary 
  FROM t
    INNER JOIN 
      ( SELECT country, max(salary) AS max_salary FROM t GROUP BY country ) tm
        ON t.country = tm.country AND t.salary = tm.max_salary

Checking .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question