Keerthi
Keerthi

Reputation: 29

How to merge multiple columns values into a single column?

I have a source report which looks like

Name Q1 Q2 Q3 Q4
A    1  2  3  4
B    5  6  7  8
C    9  0  1  2

It has to be converted into the following format

Name Quarter Value
A    Q1      1
A    Q2      2
A    Q3      3
A    Q4      4 
and so on...

I'm using SSIS for ETL. Any pointers without using hard-coded values in the T-SQL script?

Upvotes: 1

Views: 1328

Answers (1)

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58431

This would be a good match for UNPIVOT but unless you are willing to make this a dynamic sql statement, I don't see any way around hardcoding the Quarters in the statement.

SQL Statement

SELECT  Name
        , Quarter
        , Value 
FROM    q 
UNPIVOT (
          Value FOR Quarter IN (Q1, Q2, Q3, Q4)
        ) u

Test script

;WITH q (Name, Q1, Q2, Q3, Q4) AS (
    SELECT 'A', 1, 2, 3, 4
    UNION ALL SELECT 'B', 5, 6, 7, 8
    UNION ALL SELECT 'C', 9, 0, 1, 2
)
SELECT  Name
        , Quarter
        , Value 
FROM    q 
UNPIVOT (
            Value FOR Quarter IN (Q1, Q2, Q3, Q4)
        ) u

Upvotes: 1

Related Questions