How to create a pivot query

血红的双手。 提交于 2019-12-04 14:28:52

You can perform this via a PIVOT. You can use either a static PIVOT where you know the number of columns that you want to rotate or you can use a dynamic PIVOT

Static Pivot (see SQL Fiddle with Demo)

SELECT *
FROM 
(
  select *
  from t1
) x
pivot
(
  min(columnc)
  for columnb in ([X], [Y])
) p

Dynamic Pivot (see SQL Fiddle with Demo)

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(columnb) 
                    from t1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT columna, ' + @cols + ' from 
             (
                select *
                from t1
            ) x
            pivot 
            (
                min(ColumnC)
                for ColumnB in (' + @cols + ')
            ) p '

execute(@query)

Both versions will give the same results. The second works when you have an unknown number of columns that will be transformed.

Try:

DECLARE @tbl TABLE (ColumnA INT, ColumnB CHAR(1), ColumnC INT)
INSERT @tbl VALUES (111, 'X', 10), (111, 'Y', 12)

SELECT  *
FROM    @tbl
PIVOT   
(
    MAX(ColumnC) FOR ColumnB IN ([X], [Y])
) pvt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!