PostgreSQL:获得倒数第二个MAX(日期)

时间:2013-05-15 14:21:42

标签: postgresql maxdate

我在PostgreSQL中有两个视图。一个用于获取每个组织的最新总数。另一种观点是获得每个组织的倒数第二个最新总量,这就是问题:如何在PostgreSQL中获得倒数第二个MAX(日期)?这是我的代码(注意'date'是我的列之一,而不是函数):

CREATE VIEW vw_totaaldossiers AS
SELECT SUM(aantal) as totaal
FROM _dossier i1
WHERE date = (
    SELECT MAX(date) 
    FROM _dossier i2 
    WHERE i2.instantie = i1.instantie 
    GROUP BY i2.instantie
);

CREATE VIEW v2_relatiefdossiers AS
SELECT SUM(aantal) as relatief
FROM _dossier i3
WHERE date = (
    SELECT /* Here comes the second to last MAX(date) */ 
    FROM _dossier i4
    WHERE i4.instantie = i3.instantie
    GROUP BY i4.instantie
);

感谢您的帮助!

2 个答案:

答案 0 :(得分:8)

SELECT date 
FROM _dossier i2 
WHERE i2.instantie = i1.instantie 
GROUP BY i2.instantie
ORDER BY date DESC LIMIT 1 OFFSET 1

答案 1 :(得分:2)

这样的事情:

SELECT SUM(aantal) as relatief
FROM _dossier i3
WHERE date = (
    SELECT date 
    from (
       select date, 
              dense_rank() over (partition by i4.instantie order by date desc) as rnk
       FROM _dossier i4
       WHERE i4.instantie = i3.instantie
    ) t 
    where rnk = 2;
);

我不完全确定,i3实际上是在嵌套派生表中可见的!

您需要运行explain以查明Wiktor的LIMI / OFFSET查询是更快还是更慢。