3

我在 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
);

谢谢您的帮助!

4

2 回答 2

8
SELECT date 
FROM _dossier i2 
WHERE i2.instantie = i1.instantie 
GROUP BY i2.instantie
ORDER BY date DESC LIMIT 1 OFFSET 1
于 2013-05-15T14:39:13.837 回答
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 查询是更快还是更慢。

于 2013-05-15T14:40:35.207 回答