How to create a pivot query

2019-04-12 00:26发布

问题:

Imagine I have this table:

Column A | Column B | Column C
------------------------------
   111         X        10
   111         Y        12

How can I query this table to show the results like these:

Column A |     X     |      Y
-----------------------------------
   111         10           12

回答1:

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.



回答2:

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