Sql – How to create query in sql to pivot data?

pivotsqlsql server

I have two tables named PRODUCT and DETAIL

TABLE: PRODUCT
slno  product
1          x    
2          y
3          z

TABLE: DETAIL
product    detail
x          good
y          bad
z          worse
x          bad

I need to get output as

TABLE
X      Y       Z
good   bad     worse
bad

Best Answer

This data transformation is known as a PIVOT and starting in SQL Server 2005 there is a function to convert the data from rows to columns.

There are several ways that this can be done depending on whether or not you have a static number of values to transpose into columns. All of them involve adding a row_number() to the data so you can return the multiple rows of any of the products.

You can use an aggregate function with a CASE expression:

select 
  max(case when product = 'x' then detail end) x,
  max(case when product = 'y' then detail end) y,
  max(case when product = 'z' then detail end) z
from
(
  select p.product, d.detail,
    row_number() over(partition by p.product order by p.slno) rn
  from product p
  inner join detail d
    on p.product = d.product
) src
group by rn

See SQL Fiddle with Demo

You can use the PIVOT function:

select x, y, z
from
(
  select p.product, d.detail,
    row_number() over(partition by p.product order by p.slno) rn
  from product p
  inner join detail d
    on p.product = d.product
) src
pivot
(
  max(detail)
  for product in (x, y, z)
) piv

See SQL Fiddle with Demo.

If you have an unknown number of values (products in this case) to turn into columns, then you will want to use dynamic SQL:

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

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

set @query = 'SELECT ' + @cols + ' from 
             (
                select p.product, d.detail,
                  row_number() over(partition by p.product order by p.slno) rn
                from product p
                inner join detail d
                  on p.product = d.product
            ) x
            pivot 
            (
                max(detail)
                for product in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo

The result of all of the queries is:

|    X |      Y |      Z |
--------------------------
| good |    bad |  worse |
|  bad | (null) | (null) |