0

So... i got a table like this:

id  group   number  year
1   1       1       2000
2   1       2       2000
3   1       1       2001
4   2       1       2000
5   2       2       2000
6   2       1       2001
7   2       2       2001
8   2       3       2001

And i need to select the bigger number of the bigger year for each group. So i expect the result of the exemple to be:

3   1       1       2001
8   2       3       2001

any ideias? OBS: using Postgres

Allan
  • 17,141
  • 4
  • 52
  • 69

2 Answers2

2

If it's just certain rows you want to get you can use DISTINCT. If you want different maximums on the same rows you could use GROUP BY

SELECT DISTINCT ON ("group") * FROM tbl
  ORDER BY "group", year DESC, id DESC;
Simo Kivistö
  • 4,247
  • 3
  • 38
  • 42
2
SELECT *
FROM (
  SELECT *,
    row_number() over (partition by "group" order by "year" desc, "number" desc ) x
  FROM table1
) x
WHERE x = 1;

demo: http://sqlfiddle.com/#!15/cd78e/2

krokodilko
  • 35,300
  • 7
  • 55
  • 79