SQL - 选择倒数第二个日期

时间:2014-10-08 14:54:05

标签: sql

我的表格有[ArchiveDate]列,如下所示:

ArchiveDate
2014-10-06
2014-10-06
2014-10-06
2014-10-01
2014-10-01
2014-10-01
2014-10-01
2014-05-22
2014-05-22

我想选择倒数第二个日期,但是当我使用时:

select max([ArchiveDate]) -1 'previousweek'
from [PipelineArchive]

我得到2014-10-05(列中没有),而不是2014-10-01。

我无法弄清楚如何对此进行编码以选择"最后但只有一个&#34 ;;任何帮助将不胜感激!

谢谢。

3 个答案:

答案 0 :(得分:5)

您需要按降序排序ArchiveDate,跳过一条记录,然后选择下一条记录。例如,在SQL Server 2012中,您可以这样做:

SELECT DISTINCT [ArchiveDate]
FROM [PipelineArchive]
ORDER BY [ArchiveDate] DESC
OFFSET (1) ROWS FETCH NEXT (1) ROWS ONLY

Demo.

答案 1 :(得分:1)

SELECT distinct([ArchiveDate])
FROM   [PipelineArchive]
WHERE  [ArchiveDate] = (SELECT MAX([ArchiveDate]) AS second
                        FROM   [PipelineArchive]
                        WHERE  [ArchiveDate] < (SELECT MAX([ArchiveDate]) AS first
                                                FROM   [PipelineArchive])
                       )

最近的日期是:

SELECT MAX([ArchiveDate]) AS first FROM [PipelineArchive]

小于此的最大日期是:

(SELECT MAX([ArchiveDate]) AS second
 FROM   [PipelineArchive]
 WHERE  [ArchiveDate] < (SELECT MAX([ArchiveDate]) AS first
                         FROM   [PipelineArchive]))

PRO

  • 这是(非常)标准SQL

CON

  • 概括到第n个日期
  • 并不简单

答案 2 :(得分:0)

我也遇到了类似的挑战,但有时我也想抓住第n个最后一个日期,其中n = 1(最后一个日期),n = 2(倒数第二个日期),n = 3(最后三个日期).... .n = n(最早的日期)...我发现...的rank()分区做得非常好....所以以您的示例为例

;with CTE as(
select A,B,archivedate,rank() (Partition by A,B order by A,B,archivedate desc) as Nth_daterank)
select A,B,archivedate where Nth_daterank=2 
A&B的

(返回倒数第二个日期)然后可以根据需要用2代替n。