CTE与数据透视表

时间:2016-06-19 10:24:19

标签: c# sql sql-server pivot common-table-expression

我有一张桌子:TblMemberPosition

运行sql代码 -

with cte(MemberID, SponserID, Level)
  as 
    (
      select MemberID, SponserID, 1 as Level
        from TblMemberPosition
        where MemberID = 10021
      union all
      select a.MemberID, a.SponserID , Level + 1
        from TblMemberPosition as a
        inner join cte as b
          on b.MemberID = a.SponserID  
    ) 
  select (count (MemberID)) as MemberCount, Level
    From cte
    where Level <= 8
    Group by Level 
    order by Level

以上查询的结果:

MemberCount Level
1             1
1             2
3             3
1             4
2             5
1             6
1             7
2             8

但我想输出喜欢 -

MemberID    Level1   Level 2    Level 3  Level 4 .... Level upto 9
10021        1         1          3        1

此代码为单个MemberId生成。你能帮忙为所有成员生成这个结构。

2 个答案:

答案 0 :(得分:0)

with cte(MemberID, SponserID, Level)
as 
(
 select MemberID, SponserID,1 as Level from TblMemberPosition
 where MemberID = 10021
   union all
  select a.MemberID,a.SponserID,Level + 1 from TblMemberPosition
   as a inner join cte as b on b.MemberID = a.SponserID  
 ), 
ctePivotSource as (
   select 
       (count (MemberID)) as MemberCount,
       'Level ' + convert(varchar(1),[Level]) as [Level]
   from cte
   where Level <=8
   group by level
)
select *
from 
    ( select [MemberID],[MemberCount],[Level] from ctePivotSource) src
pivot 
( 
  sum(src.MemberCount) FOR [Level] in ([Level 1],[Level 2],[Level 3],[Level 4],[Level 5],[Level 6],[Level 7],[Level 8])
) as pvt

您的原始查询将列限制为8(而不是所需结果中的9),因此我还将数据限制为8列。

答案 1 :(得分:0)

这应该让你想要根级别成员,意味着没有赞助商的成员。

;WITH cte AS 
(
    SELECT  MemberID,
            SponserID,
            MemberID AS [Root] -- this will be your grouping
            0 AS [Level] -- not sure you want to count yourself
    FROM    TblMemberPosition
    WHERE   SponsorID IS NULL -- get highest level members only?
    UNION ALL
    SELECT  a.MemberID,
            a.SponserID,
            [Root],
            [Level] + 1
    FROM    TblMemberPosition AS a
            INNER JOIN cte AS b ON b.MemberID = a.SponserID
)
SELECT  [Root] AS MemberID,
        COUNT(CASE WHEN [Level] = 1 THEN 1 END) AS [Level1],
        COUNT(CASE WHEN [Level] = 2 THEN 1 END) AS [Level2],
        COUNT(CASE WHEN [Level] = 3 THEN 1 END) AS [Level3],
        COUNT(CASE WHEN [Level] = 4 THEN 1 END) AS [Level4],
        COUNT(CASE WHEN [Level] = 5 THEN 1 END) AS [Level5],
        COUNT(CASE WHEN [Level] = 6 THEN 1 END) AS [Level6],
        COUNT(CASE WHEN [Level] = 7 THEN 1 END) AS [Level7],
        COUNT(CASE WHEN [Level] = 8 THEN 1 END) AS [Level8],
        COUNT(CASE WHEN [Level] = 9 THEN 1 END) AS [Level9]
FROM    cte
GROUP BY [Root]