SQL显示前导,滞后记录

时间:2018-03-22 13:12:17

标签: sql sql-server oracle

我的表中的数据可以通过SQL显示如下:

SELECT T.VERSION_ID T_VERSION_ID
                ,cast(T.START_DATE As Date) as T_START_DATE
                ,cast(ISNULL( LEAD (START_DATE) OVER (ORDER BY START_DATE),'9999-12-31') As Date) as CALC_END_DATE_LEAD
                ,cast(ISNULL( LAG  (START_DATE) OVER (ORDER BY START_DATE),'9999-12-31') As Date) as CALC_END_DATE_LAG
FROM(select 'Vrandom1' as VERSION_ID
            ,cast('22-MAR-2018' As Date) as start_date
            ,'9999-12-31' as end_date
            , 1 as is_approved
    union
    select 'Vrandom2' as VERSION_ID
           ,cast('28-MAR-2018' As Date) as start_date
           ,'9999-12-31' as end_date
           ,1 as is_approved
    union
    select 'Vrandom3' as VERSION_ID
          ,cast('25-MAR-2018' As date) as start_date
          ,'9999-12-31' as end_date
          ,1 as is_approved
    ) as T

输出

T_VERSION_ID  T_START_DATE CALC_END_DATE_LEAD                CALC_END_DATE_LAG

Vrandom1                           22/03/2018                         25/03/2018                                         31/12/9999
Vrandom3                           25/03/2018                         28/03/2018                                         22/03/2018
Vrandom2                           28/03/2018                         31/12/9999                                         25/03/2018

此表用于应用程序内部,其中一个记录说版本“Vrandom3”将生效。为了处理,我需要根据开始日期找到即时前导和滞后记录的密钥。即我需要显示Vrandom2和Vrandom1作为领先和滞后记录的关键。

申请中的预期结果:

T_VERSION_ID  T_START_DATE    CALC_END_DATE_LEAD   CALC_END_DATE_LAG   key_leading   key_lagging

Vrandom3      25/03/2018      28/03/2018           22/03/2018          Vrandom2      Vrandom1

T_VERSION_ID  T_START_DATE   CALC_END_DATE_LEAD   CALC_END_DATE_LAG   key_leading   key_lagging

Vrandom1      22/03/2018     25/03/2018           31/12/9999          Vrandom3      null

我可以考虑加入基于start_date的内联视图,但有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

LAG (there's also LEAD) windowing function

  

访问同一结果集中前一行的数据而不使用   使用从SQL Server 2012开始的自联接.LAG提供访问权限   到达当前行之前的给定物理偏移量的行。   在SELECT语句中使用此分析函数来比较值   前一行中包含值的当前行。

这些功能旨在获得领先和滞后的行。

链接示例:

  c1 c2 c3      c4  len
0  a  b  c  [d, e]    2
2  l  m  n     [o]    1

答案 1 :(得分:0)

如何添加:

,LEAD (key_col) OVER (ORDER BY START_DATE),'9999-12-31') As Date) as Key_col_LEAD
,LAG (key_col) OVER (ORDER BY START_DATE),'9999-12-31') As Date) as Key_col_LAG

到您的SELECT