Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a pivot query

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
like image 593
Eduardo Brites Avatar asked Mar 28 '26 03:03

Eduardo Brites


2 Answers

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.

like image 177
Taryn Avatar answered Mar 29 '26 16:03

Taryn


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
like image 36
Ivan Golović Avatar answered Mar 29 '26 15:03

Ivan Golović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!