2

后台表格数据:

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
4

1 回答 1

0

它应该可以帮助你

在下面的脚本中,我检索所有成员及其赞助商

WITH Heirarchy
AS
(
   SELECT 
      0 AS [Level],
      T1.memberid,
      T1.sponsorid,
      T1.mailfirstname,
      T1.maillastname,
      T1.mailfirstname AS sponsorfname,
      T1.maillastname AS sponsorlname
   FROM
      members T1
   WHERE
      T1.sponsorid IS NULL
   UNION ALL
   SELECT
      TH.[Level] + 1 AS [Level],
      T1.memberid,
      T1.sponsorid,
      T1.mailfirstname,
      T1.maillastname,
      TH.mailfirstname,
      TH.maillastname
   FROM
      members T1
   INNER JOIN 
      Heirarchy TH ON TH.memberid = T1.sponsorid
)
SELECT * 
FROM Heirarchy
ORDER BY level, maillastname

SQLFiddle上的演示

于 2012-11-25T21:41:33.390 回答