后台表格数据:
memberid sponsorid mailfirstname maillastname
1000 NULL Foo Chu
1001 1000 Foo1 Chu1
1002 1001 Foo2 Chu2
1003 1002 Foo3 Chu3
1004 1003 Foo4 Chu4
下面的脚本打印出我当前所在的成员。但我也想同时打印该成员的赞助商信息。所以,目前我得到:
Level memberid sponsorid mailfirstname maillastname
0 1000 NULL Foo Chu
...
2 1004 1003 Foo4 Chu4
但对于 1004 会员,我还想要他们的赞助商:
Level memberid sponsorid mailfirstname maillastname sponsorfname sponsorlname
2 1004 1003 Foo4 Chu4 Foo3 Chu3
询问:
WITH Heirarchy
AS
(
SELECT
CONVERT( INT , 0 ) [Level],
T1.memberid,
T1.sponsorid,
T1.mailfirstname,
T1.maillastname
FROM
members T1
WHERE
T1.memberid = 20000283
UNION ALL
SELECT
CONVERT( INT , ( TH.[Level] + 1 ) ) [Level],
T1.memberid,
T1.sponsorid,
T1.mailfirstname,
T1.maillastname
FROM
members T1
INNER JOIN
Heirarchy TH ON TH.memberid = T1.sponsorid
)
SELECT *
FROM Heirarchy
ORDER BY level, maillastname