每个记录的倒数第二个日期

时间:2018-07-04 10:45:17

标签: sql date

我正在努力创建select,它向我显示了数据库中每个记录的倒数第二个日期。

例如:

<div class="ex0">
  <div class="ex1">
    <div style="width: 100%; height: 30px; background: red">

    </div>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
  </div>
</div>

在此记录之外,我需要写id date 1 01.01.2018 1 05.01.2018 1 06.02.2018 2 01.06.2018 2 03.06.2018 3 12.12.2017 ,向我显示以下内容:

select

任何想法怎么做?提前谢谢

4 个答案:

答案 0 :(得分:2)

使用条件聚合和ANSI标准的row_number()dense_rank()函数:

select id,
       max(date) as max_date,
       max(case when seqnum = 2 then date end) as penultimate_date
from (select t.*,
             dense_rank() over (partition by id order by date desc) as seqnum
      from t
     ) t
where seqnum in (1, 2)
group by id;

如果在平局时日期可以相同,请使用row_number()

答案 1 :(得分:1)

使用AppIcon获取GROUP BY和与另一个MAX相关的子查询,但这一次比前者要低。

MAX

答案 2 :(得分:0)

我是这样写的,

SELECT ID
    ,max(StartDate) MaxDate
    ,(
        SELECT StartDate
        FROM YourTable t2
        WHERE t2.id = t1.id
        ORDER BY StartDate DESC OFFSET 1 ROWS FETCH NEXT 1 ROW ONLY
        ) penultimate
FROM YourTable t1
GROUP BY id

答案 3 :(得分:0)

只是优化查询:

;WITH cte AS
(
    SELECT id AS ID
        ,[date] AS max_date
        ,LEAD ([date], 1, 0) OVER (PARTITION BY id ORDER BY [date] DESC) AS penultimate
        ,ROW_NUMBER() OVER(PARTITION BY id ORDER BY [date] DESC) AS RN
    FROM Table3
)
SELECT ID,max_date,penultimate
FROM cte
WHERE RN=1

SQL Fiddle