3

So normally, if I wanted to take the most recent of each type in this table:

type |    date
-----------------
  A  | 2008-07-06
  B  | 2014-08-02
  A  | 2009-12-27
  A  | 2004-03-01
  B  | 2008-10-17
  B  | 2015-01-01

I'd do this:

SELECT DISTINCT ON (type) type, date
FROM t
ORDER BY type, date DESC;

But what if I want to get not the most recent, but the second most recent? So:

type |    date
-----------------
  A  | 2008-07-06
  B  | 2014-08-02
Stephen Smith
  • 367
  • 1
  • 4
  • 12

2 Answers2

3

Hmm, looking at Grouped LIMIT in PostgreSQL: show the first N rows for each group?, I came up with:

SELECT * FROM (
  SELECT type, date, ROW_NUMBER()
  OVER (PARTITION BY type ORDER BY date DESC) AS row FROM t
  ) tmp
WHERE tmp.row=2;
Community
  • 1
  • 1
kevchoi
  • 434
  • 2
  • 7
0

you can use max instead of distinct,order by:

SELECT type,max(date) from t group by type
Ali Nikneshan
  • 3,500
  • 27
  • 39
  • There's other stuff in the row that I want. But in any case, how do I get not the max, but the next one down from the max – not the most recent date, but the second-to-most-recent one? – Stephen Smith Jan 31 '16 at 04:57
  • for other item, you can add them in group by list. for second you need nested query. `select * from (select * from order by .. desc limit 2) order by asc limit 1` – Ali Nikneshan Jan 31 '16 at 05:01