2

How would you convert a field that is stored as multiple rows into columns? I listed the code below as well. Below is an example of what is needed but it can really go up to 20 columns. Thanks!

COL1  COL2  COL3
----------------
TEST  30    NY
TEST  30    CA
TEST2 10    TN 
TEST2 10    TX

I would like the output to be :

COL1  COL2  COL3  COL4
------------------------
TEST  30    NY    CA
TEST2 10    TN    TX


select * from (
    select
    ID,
    Name,
    STORE,
    Group,
    Type,
    Date,
    State,

        row_number() over(partition by ID, state order by Date desc) as rn
    from
        #test
) t
where t.rn = 1
John
  • 452
  • 3
  • 16
  • You should use a crosstab query as described, for e.g. here: https://stackoverflow.com/questions/15714265/i-need-to-know-how-to-create-a-crosstab-query – Alexander Bell Oct 03 '17 at 20:11
  • This question has been asked 10 times + today alone. search the site ;) – Twelfth Oct 03 '17 at 22:15

2 Answers2

2
declare @Table AS TABLE
(
    Col1 VARCHAR(100)   ,
    Col2 INT    ,
    Col3 VARCHAR(100)
)
INSERT @Table
        ( Col1, Col2, Col3 )
VALUES 
( 'TEST',  30    ,'NY'     ),
( 'TEST',  30    ,'CA'     ),
( 'TEST2',  10    ,'TN'     ),
( 'TEST2',  10    ,'TX'     )


SELECT 
    xQ.Col1,
    xQ.Col2,
    MAX(CASE WHEN xQ.RowNumber = 1 THEN xQ.Col3 ELSE NULL END) AS Col3,
    MAX(CASE WHEN xQ.RowNumber = 2 THEN xQ.Col3 ELSE NULL END) AS Col4
FROM
(
    SELECT * , RANK() OVER(PARTITION BY T.Col1,T.Col2 ORDER BY T.Col1,T.Col2,T.Col3) AS RowNumber
    FROM @Table AS T
)AS xQ
GROUP BY 
    xQ.Col1,
    xQ.Col2
Bijan Ghasemi
  • 296
  • 1
  • 8
2

There are multiple options to convert data from rows into columns. In SQL, you can use PIVOT to transform data from rows into columns.

CREATE table #tablename
  (Id int, Value varchar(10), ColumnName varchar(15);


INSERT INTO #tablename
  (ID,  Value, ColumnName)

VALUES
  (1, ‘Lucy’, 'FirstName'),
  (2, ‘James’, ‘LastName’),
  (3, ‘ABCDXX’, ‘Adress’),
  (4, ’New York’, ‘City’),
  (5, '8572685', ‘PhoneNo’);

select FirstName, LastName, Address, City, PhoneNo
from
(
 select Value, ColumnName
 from #tablename
) d
pivot
(
 max(Value)
 for ColumnName in (FirstName, LastName, Address, City, PhoneNo)
) piv;

Refer the below link for other options of transforming data from rows to columns:

https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

nish
  • 1,201
  • 6
  • 8