我有一张桌子
DATE LEAVEDAYS NXTWRKDAYS
2014-07-01 No NULL
2014-07-02 No NULL
2014-07-03 No NULL
2014-07-04 No NULL
2014-07-05 Yes NULL
2014-07-06 Yes NULL
2014-07-07 Yes NULL
2014-07-08 No NULL
2014-07-09 Yes NULL
2014-07-10 Yes NULL
2014-07-11 No NULL
输出
DATE LEAVEDAYS NXTWRKDAYS
2014-07-01 No 2014-07-02
2014-07-02 No 2014-07-03
2014-07-03 No 2014-07-04
2014-07-04 No 2014-07-05
2014-07-05 Yes 2014-07-08
2014-07-06 Yes 2014-07-08
2014-07-07 Yes 2014-07-08
2014-07-08 No 2014-07-09
2014-07-09 Yes 2014-07-11
2014-07-10 Yes 2014-07-11
2014-07-11 No 2014-07-12
可以看出,在2014-07-04之后,下一个工作日是' 2014-07-08'从此以后,2014-07-05之后的产量是2014-07-08。 2014-07-10之后,下一个工作日是2014-07-11'从此以后,2014-07-10之后的产出是2014-07-11
脚本
declare @t table([DATE] DATE,LEAVEDAYS Varchar(10),NXTWRKDAYS DATE)
insert into @t Values
('2014-07-01','No',NULL),
('2014-07-02','No',NULL),
('2014-07-03','No',NULL),
('2014-07-04','No',NULL),
('2014-07-05','Yes',NULL),
('2014-07-06','Yes',NULL),
('2014-07-07','Yes',NULL),
('2014-07-08','No',NULL),
('2014-07-09','Yes',NULL),
('2014-07-10','Yes',NULL),
('2014-07-11','No',NULL)
select *
from @t
答案 0 :(得分:3)
检查此查询,希望它可以帮助您:
您的创建表和插入脚本:
declare @t table([DATE] DATE,LEAVEDAYS Varchar(10),NXTWRKDAYS DATE)
insert into @t Values
('2014-07-01','No',NULL),
('2014-07-02','No',NULL),
('2014-07-03','No',NULL),
('2014-07-04','No',NULL),
('2014-07-05','Yes',NULL),
('2014-07-06','Yes',NULL),
('2014-07-07','Yes',NULL),
('2014-07-08','No',NULL),
('2014-07-09','Yes',NULL),
('2014-07-10','Yes',NULL),
('2014-07-11','No',NULL)
必填项:
SELECT
t.date AS Date,
t.leavedays AS LeaveDays,
CASE WHEN t.LEAVEDAYS = 'No' THEN DATEADD(day,1, t.DATE)
WHEN t.LEAVEDAYS = 'Yes' THEN (Select top 1 t1.date from @t t1 WHERE t1.date > t.DATE and t1.LEAVEDAYS = 'No' ORDER BY t1.date)
ELSE null END AS NxtWorkingDay
FROM @t t
答案 1 :(得分:1)
您可以使用APPLY
和TOP
:
SELECT
t.[DATE],
t.LEAVEDAYS,
NXTWRKDAYS = x.[DATE]
FROM @t t
OUTER APPLY(
SELECT TOP 1 [DATE]
FROM @t
WHERE
[DATE] > t.[DATE]
AND LEAVEDAYS = CASE WHEN t.LEAVEDAYS = 'YES' THEN 'NO' ELSE LEAVEDAYS END
) x