如何从第二个日期到最晚日期获取所有行?

时间:2018-05-09 17:50:25

标签: sql postgresql

我已经获得了最新日期的所有行:

SELECT      date, quarter, sales_region, revenue
FROM        regions
WHERE       date = (SELECT MAX(date) FROM regions)
ORDER BY    1

那么我如何得到第二个最新日期的行?

我试过但没有运气:

SELECT      MAX(date), quarter, sales_region, revenue
FROM        regions
WHERE       date < (SELECT MAX(date) FROM regions)
ORDER BY    1

2 个答案:

答案 0 :(得分:0)

这是一种方法:

SELECT date, quarter, sales_region, revenue
FROM regions
WHERE date = (SELECT DISTINCT date
              FROM regions r2
              ORDER BY date DESC
              OFFSET 1 FETCH FIRST 1 ROW ONLY
             )
ORDER BY 1;

另一种方法使用dense_rank()

select r.*
from (select r.*, dense_rank() over (order by date desc) as seqnum
      from regions r
     ) r
where seqnum = 2;

答案 1 :(得分:0)

Gordon准确地回答了您的问题,但如果您想在一个查询中获取最后两个日期的记录,则可以使用IN代替=,并使用{获取前两个记录{1}}:

LIMIT 2

从版本8.4开始,您也可以使用SELECT date, quarter, sales_region, revenue FROM regions WHERE date IN (SELECT DISTINCT date FROM regions r2 ORDER BY date DESC LIMIT 2) ORDER BY 1; 代替FETCH FIRST 2 ROW ONLY