基于连续日逻辑向SQL查询添加其他标志值

时间:2016-12-28 18:22:09

标签: sql sql-server flags

我有一个包含以下结构的表

Date            Holiday Flag     
12/23/2016      -1               
12/24/2016      -1               
12/25/2016       1               
12/26/2016       1               
12/27/2016      -1               

我想添加一个基于上面提到的两列的附加标志

Date            Holiday Flag     Previous Flag
12/23/2016      -1               -1
12/24/2016      -1               -1
12/25/2016       1               -1
12/26/2016       1                1
12/27/2016      -1               -1

基本上,如果连续两天(2016年12月25日和2016年12月26日)有假期,我希望“上一个标志”在第二天(2016年12月26日)反映出来为1

我正在使用SQL Server 2008来构建查询,但似乎无法弄清楚逻辑。

解决这种情况的最佳方法是什么?提前感谢您的帮助,我是编程新手。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:1)

借助CTE和Row_Number()

Declare @YourTable table (Date date, [Holiday Flag] int)
Insert Into @YourTable values
('12/23/2016',-1),
('12/24/2016',-1),               
('12/25/2016', 1),               
('12/26/2016', 1),               
('12/27/2016',-1)

;with cte as (
Select *
      ,RN = Row_Number() over (Order By Date)
 From  @YourTable
) 
Select A.Date
      ,A.[Holiday Flag]
      ,[Previous Flag] = IsNull(B.[Holiday Flag],A.[Holiday Flag])
 From  cte A
 Left Join cte B on (B.RN=A.RN-1)
 Order By A.Date

返回

enter image description here

不确定我是否同意所需的结果。我将12/27前一个标志显示为1

答案 1 :(得分:1)

这可能有用。

DECLARE @T TABLE (Date DATETIME,HolidayFlag INT)
INSERT INTO @T SELECT '12/23/2016',-1
INSERT INTO @T SELECT '12/24/2016',-1
INSERT INTO @T SELECT '12/25/2016',1
INSERT INTO @T SELECT '12/26/2016',1
INSERT INTO @T SELECT '12/27/2016',-1

SELECT
    This.Date,
    This.HolidayFlag,
    LastHolidayFlag=CASE WHEN Last.Date IS NULL THEN -1 ELSE Last.HolidayFlag END
FROM
(
    SELECT Date,HolidayFlag,RowNumber=ROW_NUMBER() OVER (ORDER BY Date) FROM @T
)AS This
LEFT OUTER JOIN
(
    SELECT Date,HolidayFlag, RowNumber=ROW_NUMBER() OVER (ORDER BY Date)  FROM @T
)AS Last ON Last.RowNumber=This.RowNumber-1

答案 2 :(得分:0)

不太复杂。试试这个。

Declare @Table table (Date date, [Holiday Flag] int)
Insert Into @Table values
('12/23/2016',-1),
('12/24/2016',-1),               
('12/25/2016',1),               
('12/26/2016',1),               
('12/27/2016',-1)

Select A.Date
      ,A.[Holiday Flag]
      ,[Previous Flag] = IsNull(B.[Holiday Flag],A.[Holiday Flag])
 From  @Table A
 Left Join @Table B on (DateAdd(day,-1 , A.Date)=B.Date)
 Order By A.Date

答案 3 :(得分:0)

由于您有连续日期,因此ROW_NUMBER()是多余的。试试这个:

Declare @MyTbl table (
    Dt date PRIMARY KEY, 
    HolidayFlag int
    )

Insert Into @MyTbl 
values
    ('12/23/2016',-1),
    ('12/24/2016',-1),               
    ('12/25/2016', 1),               
    ('12/26/2016', 1),               
    ('12/27/2016',-1)

SELECT t1.Dt as [Date], 
    t1.HolidayFlag as [Holiday Flag],
    CASE
        WHEN t1.HolidayFlag = 1
            THEN IsNull(t2.HolidayFlag, -1)
        ELSE -1
    END as [Previous Flag]
FROM @MyTbl t1
LEFT JOIN @MyTbl t2
    ON t2.dt = dateadd(day, -1, t1.dt)