Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server rows to columns

My query is:

SELECT vendor.id, insurances.id AS ins_id, vendor_insurances.expiry_date
FROM vendor
INNER JOIN vendor_insurances
ON vendor.id=vendor_insurances.vendor_id

and the output:

id    ins_id    expiry_date
================================
28    1         2006-01-01
28    11        2008-01-01

I want to convert it to:

id    1            11
======================================
28    2006-01-01   2008-01-01

Thanks,

like image 291
riz Avatar asked Feb 20 '23 07:02

riz


1 Answers

You will need to use PIVOT and do something similar to this:

Static Pivot - for just a few number of columns that you will pivot

select *
from 
(
  SELECT v.id
    , vi.id AS ins_id
    , vi.expiry_date
  FROM vendor v
  INNER JOIN vendor_insurances vi
    ON v.id=vi.vendorId
) x
PIVOT
(
   MIN(expiry_date)
    FOR ins_id IN ([1], [11])
) p

See SQL Fiddle for Working Demo

Or you can use a Dynamic Pivot if you have a lot of items to PIVOT:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(vi.id) 
                  FROM vendor v
                  INNER JOIN vendor_insurances vi
                    ON v.id=vi.vendorId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, ' + @cols + ' from 
             (
                SELECT v.id
                    , vi.id AS ins_id
                    , vi.expiry_date
                FROM vendor v
                INNER JOIN vendor_insurances vi
                    ON v.id=vi.vendorId
            ) x
            pivot 
            (
                MIN(expiry_date)
                for ins_id in (' + @cols + ')
            ) p '

execute(@query)

Both will give you the same results.

like image 165
Taryn Avatar answered Feb 27 '23 02:02

Taryn