Question

I have scenario like

Account_Number | Ins1     |Ins2  | Ins3
8923647324     | 3        | 1    |  5
128736244      | 5        | 2    |  6
9238475323     | 6        | 3    |  7

I wanted to achieve something like

8923647324     | 3     
8923647324     | 1      
8923647324     | 5
128736244      | 5
128736244      | 2
128736244      | 6  

It can be done using UNION. But looking for some inbuilt feature, which won't affect performance of data retrieval. And, I don't have any clue. Anyone help me on this.

Was it helpful?

Solution

There are many ways to do this:

Using UNION

SELECT  Account_Number,
        Ins1 AS Ins
FROM YourTable
UNION ALL
SELECT  Account_Number,
        Ins2
FROM YourTable
UNION ALL
SELECT  Account_Number,
        Ins3
FROM YourTable

Using CROSS APPLY:

SELECT  t.Accoun_Number,
        x.Ins
FROM YourTable t
CROSS APPLY 
(
    VALUES
        (t.Ins1),
        (t.Ins2),
        (t.Ins3)
) x (Ins);

I would add one way using UNPIVOT, but I'll leave that for you to research.

OTHER TIPS

You can use UNPIVOT

SELECT Account_Number, Ins
FROM tbl
UNPIVOT
(
    Ins FOR Val IN (Ins1, Ins2, Ins3)   
) as unp
select Account_Number, Ins1 as Value from mytable 
UNION ALL
select Account_Number, Ins2 as Value from mytable
UNION ALL
select Account_Number, Ins3 as Value from mytable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top