我有一個表結構如下SQL遞歸CTE - 請參考親
userId userName managerId
----------- ---------------- -----------
1 John NULL
2 Charles 1
3 Nicolas NULL
4 Neil 3
而且我有具有以下
userId shareId
----------- -----------
1 1001
3 1002
所以我下面的查詢到另一個表讓我的遞歸CTE:
WITH UserCTE AS (
SELECT userId, userName, managerId,0 AS steps
FROM dbo.Users
WHERE userId = 7
UNION ALL
SELECT mgr.userId, mgr.userName, mgr.managerId, usr.steps +1 AS steps
FROM UserCTE AS usr
INNER JOIN dbo.Users AS mgr
ON usr.managerId = mgr.userId
)
SELECT * FROM UserCTE AS u;
將會產生以下結果
userId userName managerId steps
----------- ---------------- ----------- -----------
1 John NULL 0
2 Charles 1 1
3 Nicolas NULL 0
4 Neil 3 1
好吧,我想知道的是shareId
爲擁有它的用戶,也爲屬於他們的用戶。
預期結果:
userId userName managerId steps shareId
----------- ---------------- ----------- ----------- ----------
1 John NULL 0 1001
2 Charles 1 1 1001
3 Nicolas NULL 0 1002
4 Neil 3 1 1002
有什麼辦法實現呢?
感謝
非常感謝,這正是我所期待的。 – user3362714 2015-01-10 19:32:59