SQL PIVOT结果集

时间:2014-09-23 23:14:25

标签: sql sql-server pivot

寻找旋转结果集的帮助,因为我对它很新。

这里我将测试数据插入表中。

        CREATE TABLE #temp (procCode int, member_id varchar(10))

        INSERT INTO #temp(procCode,member_id)
        SELECT 90658,'jjjj'
        UNION all
        SELECT 90658,'k'
        UNION all
        SELECT 90658,'jjjkk'
        UNION all
        SELECT 90658,'jjjj'
        UNION all
        SELECT 90658,'k'
        UNION all
        SELECT 90658,'jjjkk'
        UNION all
        SELECT 90658,'jjjj'
        UNION all
        SELECT 90658,'k'
        UNION all
        SELECT 90649,'jjjj'
        UNION all
        SELECT 90649,'k'
        UNION all
        SELECT 906,'jjjj'
        UNION all
        SELECT 906,'jjjj'


        select 
         member_id,procCode, COUNT(*) as countProcCode
        FROM #temp
        GROUP BY member_id,procCode

现在输出如下数据:

member_id      procCode     CountProcCode
jjjj             906               2       
jjjj             90649             1
jjjkk             90658            2
  k              90649             1
jjjj             90658             3   
 k                90658            3

我需要它显示如下:

member_id    Count906    count90649     count90658
jjjj         2              1              3
k             0             1              3
jjjkk         0             0              2

非常感谢任何帮助。 不仅仅是这些procCodes和member_id,所以我无法真正说出(506,50658,50649)中的member_id,因为还有其他的可能出现。

1 个答案:

答案 0 :(得分:0)

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.procCode) 
            FROM #temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT member_id, ' + @cols + ' from 
            (
                select member_id, member_id as b
                    , procCode

                from #temp
           ) x
            pivot 
            (
                 count(b)
                for procCode in (' + @cols + ')
            ) p '


execute(@query)

drop table #temp

结果

member_id   906 90649   90658
jjjj        2   1       3
jjjkk       0   0       2
k           0   1       3

Recomended reading