选择第二个最近日期的条目

时间:2016-01-31 04:40:55

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

通常,如果我想在此表中采用每种类型的最新类型:

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

我这样做:

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

但是,如果我想要的不是最新的,而是最近的第二次呢?所以:

type |    date
-----------------
  A  | 2008-07-06
  B  | 2014-08-02

2 个答案:

答案 0 :(得分:3)

嗯,看着Grouped LIMIT in PostgreSQL: show the first N rows for each group?,我想出了:

                    switch (n) {
                        case 0: a[j] = buffer.substring(k, k + 1); break;
                        case 1: b[j] = buffer.substring(k, k + 1); break;
                        case 2: c[j] = buffer.substring(k, k + 1); break;
                        case 3: d[j] = buffer.substring(k, k + 1); break;
                        case 4: e[j] = buffer.substring(k, k + 1); break;
                        case 5: f[j] = buffer.substring(k, k + 1); break;
                        case 6: g[j] = buffer.substring(k, k + 1); break;
                        default: break;

答案 1 :(得分:0)

您可以使用max而不是distinct,按:

排序
SELECT type,max(date) from t group by type