我的数据看起来像这样
col1; col2; col3; col4; sort; desc; levels
1 1 1 1 10 ab null
1 1 1 2 20 c 1
1 1 1 3 30 d null
1 1 1 4 40 e null
1 1 1 5 50 fg 1
1 1 1 6 60 hij 1
1 1 1 7 70 k 1
所需的输出如下所示
col1; col2; col3; col4; desc; addDesc
1 1 1 1 ab null
1 1 1 2 c ab
1 1 1 3 d null
1 1 1 4 e null
1 1 1 5 fg e
1 1 1 6 hij e
1 1 1 7 k e
逻辑是每当列LEVELS不为空时,从LECELS为空的先前DESC获取值。 我希望你们明白这一点!
提前谢谢大家!
答案 0 :(得分:2)
您可以使用OUTER APPLY
:
SELECT t1.col1,
t1.col2,
t1.col3,
t1.col4,
t1.[desc],
CASE
WHEN t1.levels IS NOT NULL THEN t2.[desc]
END [addDesc]
FROM dbo.YourTable t1
OUTER APPLY (SELECT TOP 1 [desc]
FROM dbo.YourTable
WHERE levels IS NULL
AND sort < t1.sort
ORDER BY sort DESC) t2;