如何从多列中选择树

时间:2018-06-25 05:41:01

标签: sql sql-server sql-server-2012

具有这样的数据

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' P1A1的根,A1AA1的根,而A1是{ AA4中的{1}}。这就是为什么输出必须像这样:

'P1','A1','AA4'

Sqlfiddle:http://www.sqlfiddle.com/#!18/87eb3/1

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