我正在尝试在分层数据集上编写复杂的CASE
语句。
这是包含样本数据的表格:
Level Parent Child IsDirector
----------------------------------------
0 NULL SteveJobs NO
1 SteveJobs TimCook YES
2 TimCook Greg NO
3 Greg Mark NO
4 Mark Jack NO
4 Mark Kim NO
4 Mark Tyler NO
4 Mark Emma NO
我正在尝试编写SQL查询来查找某个人的导演。如果我查询Kim,结果应该是这样的。
Parent Child Director
-------------------------
Mark Kim TimCook
这是我写的查询。
SELECT
A.Parent, A.Child,
CASE A.IsDirector
WHEN 'YES'
THEN A.Child
WHEN 'NO'
THEN CASE
WHEN (A.IsDirector = 'NO' AND A.Parent IS NOT NULL)
THEN A.Parent
ELSE (SELECT
CASE WHEN B.IsDirector = 'YES'
THEN B.Parent
END AS Director
FROM @Org B
WHERE B.Child = A.Parent)
END
END AS Director,
A.IsDirector
FROM
@Org A
WHERE
Child = 'Kim'
结果是
Parent Child Director IsDirector
------------------------------------
Mark Kim Mark NO
下面是SQL小提琴。抱歉,我不知道如何格式化上述代码。
答案 0 :(得分:0)
也许有一个递归的cte
Declare @YourTable table (Level int,Parent varchar(50),Child varchar(50),IsDirector varchar(50))
Insert into @YourTable values
(0,NULL,'SteveJobs','NO'),
(1,'SteveJobs','TimCook','YES'),
(2,'TimCook','Greg','NO'),
(3,'Greg','Mark','NO'),
(4,'Mark','Jack','NO'),
(4,'Mark','Kim','NO'),
(4,'Mark','Tyler','NO'),
(4,'Mark','Emma','NO')
Declare @Fetch varchar(50)='Kim'
;with cteHB as (
Select Child
,Parent
,Lvl=1
,Director=case when IsDirector='Yes' then Child else '' end
From @YourTable
Where Child=@Fetch
Union All
Select R.Child
,R.Parent
,P.Lvl+1
,Director=case when IsDirector='Yes' then R.Child else '' end
From @YourTable R
Join cteHB P on P.Parent = R.Child)
Select A.*
,B.Director
From @YourTable A
Join cteHB B on (A.Child=@Fetch and Director<>'')
返回
Level Parent Child IsDirector Director
4 Mark Kim NO TimCook
只是为了好玩,要查看路径,您可以用
替换文件SELECTSelect Lvl = Row_Number() over (Order By Lvl Desc)
,Child
,Parent
,Director
From cteHB
Order By 1