具有这样的数据
DECLARE @tbl TABLE (name1 varchar(5),name2 varchar(5),name3 varchar(5))
INSERT INTO @tbl(name1,name2,name3)
values ('P1','A1','AA1'),('P1','B1','AA2'),('P1','C1','AA3'),('P1','A1','AA4')
输入表为:
name1 name2 name3
P1 A1 AA1
P1 B1 AA2
P1 C1 AA3
P1 A1 AA4
我想从这棵有点奇怪的树中选择,结果必须是这样的:
col1 col2
P1 A1
A1 AA1
A1 AA4
P1 B1
B1 AA2
P1 C1
C1 AA4
第一行的示例'P1','A1','AA1'
P1
是A1
的根,A1
是AA1
的根,而A1
是{ AA4
中的{1}}。这就是为什么输出必须像这样:
'P1','A1','AA4'
Sqlfiddle:http://www.sqlfiddle.com/#!18/87eb3/1
答案 0 :(得分:1)
也许您想要的是这样的东西
SELECT col1, col2
FROM
(
SELECT name2 AS child, 0 AS type, name1 AS col1, name2 AS col2
FROM @tbl
UNION
SELECT name2 AS child, 1 AS type, name2 AS col1, name3 AS col2
FROM @tbl
) AS t
ORDER BY child DESC, type, col1, col2
示例输出:
col1 col2
------------
P1 C1
C1 AA3
P1 B1
B1 AA2
P1 A1
A1 AA1
A1 AA4