Identify sub-set of records based on date and rules in SQL Server

怎甘沉沦 提交于 2019-12-06 02:41:00
sagi

You can use LAG() and LEAD() analytic functions:

SELECT * FROM (
    SELECT t.*,
           LAG(t.linked,1,0) OVER(ORDER BY t.FromDate DESC) as rnk_1, --Next one
           LEAD(t.linked,1,0) OVER(ORDER BY t.FromDate DESC) as rnk_2, -- Last one,
           LEAD(t.linked,2,0) OVER(ORDER BY t.FromDate DESC) as rnk_3 -- Last two,
    FROM YourTable t) s
WHERE ((s.rnk_1 = 1 OR s.rnk_2 = 1) AND s.linked = 1) OR 
      (s.rnk_2 = 1 and s.rnk_3 = 1 and s.linked = 0)
ORDER BY s.FromDate DESC

This will result in records that have linked = 1 and the previous/next record is also 1.

Using LAG and LEAD functions you can examine the previous/next row values given a sort criteria.

You can achieve your required dataset using the following DDL:

;
WITH    CTE_LagLead
          AS (
              SELECT    FromDate,
                        ToDate,
                        NoOfDays,
                        Weeks,
                        Linked,
                        LAG(Linked, 1, 0) OVER (ORDER BY ToDate DESC) LinkedLag,
                        LEAD(Linked, 1, 0) OVER (ORDER BY ToDate DESC) LinkedLead
              FROM      @table
             )
    SELECT  FromDate,
            ToDate,
            NoOfDays,
            Weeks,
            Linked
    FROM    CTE_LagLead
    WHERE   Linked = 1 AND
            (LinkedLag = 1 OR
             LinkedLead = 1)
    ORDER BY ToDate DESC;

See working example

here is the answer I came up with:

Select 
    * 
from 
    #tmpAbsences 
where 
    idcol between 1 AND (
    Select TOP 1 idcol from #tmpAbsences where Linked=0)

this includes the row 7 in the below picture:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!