簡體   English   中英

SQL多重自我聯接到列

[英]SQL multiple self joins to columns

我在名為套件的表格中有以下簡化信息,很遺憾,我無法控制

id  title            parentsuiteid
1   test             NULL
4   pay1             3
5   pay2             3
3   Bill Payments    2
14  Vouchers         2
15  Mini             2
2   Site Tests       NULL

我想使用水平表示法進行報告,例如

test
Site tests   Bill Payments  pay1
Site tests   Bill Payments  pay2
Site tests   Vouchers   
Site tests   Mini   

我正在測試加入

select a.id,a.title,b.title,a.parentsuiteid from #temp2 a
left outer join #temp2 b
on a.id = b.parentsuiteid

id  title           title       parentsuiteid
1   test            NULL            NULL
4   pay1            NULL            3
5   pay2            NULL            3
3   Bill Payments   pay1            2
3   Bill Payments   pay2            2
14  Vouchers        NULL            2
15  Mini            NULL            2
2   Site Tests      Bill Payments   NULL
2   Site Tests      Vouchers        NULL
2   Site Tests      Mini            NULL 

這可以在兩個級別上正常工作,但我無法預測將來會有多少個級別,而且似乎有兩個以上級別會變得復雜

我如何使我的輸出看起來像+-5級的水平表示?

嘗試這個:

SQL小提琴

MS SQL Server 2008架構設置

CREATE TABLE temp
(
  ID int,
  title VARCHAR(50),
  parentsuiteid int null
)

INSERT INTO temp
VALUES
(1, 'test', NULL),
(4, 'pay1',3),
(5, 'pay2', 3),
(3, 'Bill Payments', 2),
(14, 'Vouchers', 2),
(15, 'Mini', 2),
(2, 'Site Tests', NULL)

查詢1

;WITH recurs
AS
(
    SELECT ID, title, parentsuiteid, 0 as level
    FROM Temp
    WHERE parentsuiteid IS NULL
    UNION ALL
    SELECT t1.ID, CAST(t2.title + ' ' + t1.title as VARCHAR(50)), t1.parentsuiteid, t2.level + 1 
    FROM temp t1
    INNER JOIN recurs t2
        ON t1.parentsuiteid = t2.ID
)
SELECT title
FROM Recurs r1
WHERE NOT EXISTS (SELECT * from recurs r2 WHERE r2.parentsuiteid = r1.Id )

結果

|                         TITLE |
|-------------------------------|
|                          test |
|           Site Tests Vouchers |
|               Site Tests Mini |
| Site Tests Bill Payments pay1 |
| Site Tests Bill Payments pay2 |

您可以使用遞歸CTE:

WITH EmpsCTE
AS (
 SELECT empid
    ,mgrid
    ,firstname
    ,lastname
    ,0 AS distance
FROM HR.Employees
WHERE empid = 9

UNION ALL

SELECT M.empid
    ,M.mgrid
    ,M.firstname
    ,M.lastname
    ,S.distance + 1 AS distance
FROM EmpsCTE AS S
INNER JOIN HR.Employees AS M ON S.mgrid = M.empid
)
SELECT empid
,mgrid
,firstname
,lastname
,distance
FROM EmpsCTE;

empid       mgrid       firstname  lastname             distance 
----------- ----------- ---------- -------------------- ----------- 
9           5           Zoya       Dolgopyatova         0 
5           2           Sven       Buck                 1 
2           1           Don        Funk                 2 
1           NULL        Sara       Davis                3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM