我有一张包含连续日期列表的表格。该表还具有日类型字段,其包括:营业日(B),星期六(X),星期日(Y)和假日(H)
我想添加一个具有递增数字的附加列。 该数字只应在以下情况下递增:
期望的结果:
DATE DAY_TYPE NUMBER
2017-03-09 B 1
2017-03-10 B 2
2017-03-11 X 3
2017-03-12 Y 3
2017-03-13 H 3
2017-03-14 B 3
2017-03-15 B 4
2017-03-16 H 5
2017-03-17 B 5
答案 0 :(得分:0)
您可以使用递归common table expression
执行此操作DECLARE @sample TABLE ( [date] DATE, day_type CHAR(1))
INSERT @sample
( [date], day_type )
VALUES
('2017-03-09','B')
,('2017-03-10','B')
,('2017-03-11','X')
,('2017-03-12','Y')
,('2017-03-13','H')
,('2017-03-14','B')
,('2017-03-15','B')
,('2017-03-16','H')
,('2017-03-17','B')
;WITH cteSample
AS(
SELECT
ROW_NUMBER()OVER(ORDER BY [S].[date]) 'RN'
, S.[date]
, S.day_type
FROM @sample S
),cteRecursive
AS(
SELECT
b.RN, b.[date], b.day_type, 1 'Number'
FROM
cteSample b
WHERE
b.RN = 1 AND b.day_type = 'B'
UNION ALL
SELECT
e.RN, e.[date], e.day_type
,CASE WHEN ( e.day_type IN ('B') AND r.day_type IN ('B') OR e.day_type NOT IN ('B') AND r.day_type IN ('B') )
THEN r.Number + 1 ELSE r.Number END
FROM
cteSample e
INNER JOIN
cteRecursive r ON e.RN = r.rn + 1
)
SELECT * FROM cteRecursive