如何找到每个子记录的顶级父级

时间:2015-08-21 01:47:50

标签: sql sql-server sql-server-2008

我正在使用SQL Server 2008。

我在表trans中有两列数据:

transid      ptransid
---------------------
1            1
2            2
3            3
4            1
5            3
6            2
7            2
8            7
9            8
10           4

我想将结果显示为

transid      ptransid
----------------------
1            1
2            2
3            3
4            1
5            3
6            2
7            2
8            2
9            2
10           1

查询:

select 
    T0.transid, T3.ptransid
from 
    trans T0
left join 
    trans T1 on T0.ptransid = T1.transid
left join 
    trans T2 on T1.ptransid = T2.transid
left join 
    trans T3 on T2.ptransid = T3.transid

但上面的例子太简单了。该层可以具有30,因为上述样品仅为4。

1 个答案:

答案 0 :(得分:2)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE test_table(transid INT, ptransid INT)
INSERT INTO test_table VALUES
(1    ,        1),
(2    ,        2),
(3    ,        3),
(4    ,        1),
(5    ,        3),
(6    ,        2),
(7    ,        2),
(8    ,        7),
(9    ,        8),
(10   ,        4)

查询1

WITH c AS (
         SELECT transid, 
                ptransid, 
                ptransid AS topptransid 
         FROM   test_table 
         WHERE  transid = ptransid 
         UNION ALL 
         SELECT T.transid, 
                T.ptransid, 
                c.topptransid 
         FROM   test_table AS T 
                INNER JOIN c 
                        ON T.ptransid = c.transid 
         WHERE  T.transid <> T.ptransid) 
SELECT transid, 
       topptransid 
FROM   c 
ORDER  BY transid 

<强> Results

| transid | topptransid |
|---------|-------------|
|       1 |           1 |
|       2 |           2 |
|       3 |           3 |
|       4 |           1 |
|       5 |           3 |
|       6 |           2 |
|       7 |           2 |
|       8 |           2 |
|       9 |           2 |
|      10 |           1 |