Hi folks,Say I have the following table:DECLARE @Sample TABLE (Code INT, Row TINYINT, Mail VARCHAR(200))INSERT INTO @SampleSELECT 1111, 1, 'abc@yahoo.com'UNION ALL SELECT 1111, 2, 'xyz@yahoo.com'UNION ALL SELECT 1111, 3, NULLUNION ALL SELECT 2222, 1, 'abc2@yahoo.com'UNION ALL SELECT 2222, 2, NULLUNION ALL SELECT 2222, 3, 'xyz2@yahoo.com'
and I want to get it into the format:DECLARE @Sample2 TABLE (Code INT, Mail1 VARCHAR(200), Mail2 VARCHAR(200), Mail3 VARCHAR(200))
I would use the following query:SELECT Code, [1] Mail1, [2] Mail2, [3] Mail3FROM ( SELECT Code, Row, Mail FROM @Sample ) sPIVOT ( MIN(Mail) FOR Row IN ([1], [2], [3])) AS p
Now what if in the initial @Sample table looks like this (an extra phone column):DECLARE @Sample TABLE (Code INT, Row TINYINT, Mail VARCHAR(200), Phone VARCHAR(200))INSERT INTO @SampleSELECT 1111, 1, 'abc@yahoo.com', '123456'UNION ALL SELECT 1111, 2, 'xyz@yahoo.com', '234567'UNION ALL SELECT 1111, 3, NULL, NULLUNION ALL SELECT 2222, 1, 'abc2@yahoo.com', '345678'UNION ALL SELECT 2222, 2, NULL, NULLUNION ALL SELECT 2222, 3, 'xyz2@yahoo.com', '456789'
and I want to get the data into the following format:DECLARE @Sample2 TABLE (Code INT, Mail1 VARCHAR(200), Mail2 VARCHAR(200), Mail3 VARCHAR(200), Phone1 VARCHAR(200), Phone2 VARCHAR(200), Phone3 VARCHAR(200))
the only query that I found that works is the following:SELECT a.Code, a.[1] Mail1, a.[2] Mail2, a.[3] Mail3, b.[1] Phone1, b.[2] Phone2, b.[3] Phone3 FROM ( SELECT Code, [1], [2], [3] FROM ( SELECT Code, Row, Mail FROM @Sample ) s PIVOT ( MIN(Mail) FOR Row IN ([1], [2], [3]) ) AS p) AS aINNER JOIN ( SELECT Code, [1], [2], [3] FROM ( SELECT Code, Row, Phone FROM @Sample ) s PIVOT ( MIN(Phone) FOR Row IN ([1], [2], [3]) ) AS p) AS bON a.Code = b.Code
So for each column that I need to pivot (in the last example, two columns), I need a different select, PIVOT and join.My real world scenario requires about 8 columns to be pivoted (is there such a word? :) )So I would need 8 different selects, PIVOTs and seven joins.Is there another, simpler and more efficient way to do this?I'm using SQL Server 2005.