使用自定义字符串进行透视和格式结果集

时间:2017-11-28 21:56:12

标签: sql sql-server-2012

我正在使用SQL Server 2014.想知道获得下表结果的更好方法。 来源表

UserId --- Program 
100 --------        P1
100 -------- P2
101 -------- P3
103 --------  P1

期望输出

UserId ------ P1 --- P2 ----P3
100  -------- YES----YES----NO
101  -------- NO ---- NO ---YES
103 -------- YES ---- NO --YES

请注意

UserId,程序是动态填充的。

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是:

SELECT userid, 
       CASE 
         WHEN Sum(CASE 
                    WHEN program = 'p1' THEN 1 
                    ELSE 0 
                  END) = 1 THEN 'YES' 
         ELSE 'No' 
       END AS p1, 
       CASE 
         WHEN Sum(CASE 
                    WHEN program = 'p2' THEN 1 
                    ELSE 0 
                  END) = 1 THEN 'YES' 
         ELSE 'No' 
       END AS p2, 
       CASE 
         WHEN Sum(CASE 
                    WHEN program = 'p3' THEN 1 
                    ELSE 0 
                  END) = 1 THEN 'YES' 
         ELSE 'No' 
       END AS p3 
FROM   table
GROUP  BY userid 

动态地你可以这样做:

create table #temp 
(
    userid int,
    program varchar(20)

)

insert into #temp
values(100, 'P1'),
(100 ,'P2'),
(101 , 'P3'),
(103 ,  'P1')

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


SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.program) 
            FROM #temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
SET @computedCols = STUFF((SELECT distinct ',' + ' case when ' + QUOTENAME(c.program) + ' = 1 Then ''Yes'' ELSE ''NO'' end as '+  QUOTENAME(c.program)
            FROM #temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT userid, ' + @computedCols + ' from 
            (
                select *, 1 as val
                from #temp
           ) x
            pivot 
            (
                 max(val)
                for program in (' + @cols + ')
            ) p '


execute(@query)

以上是此帖[{3}}

中接受的答案的延伸