Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include NULL values in unpivot

I have been looking for a solution for this problem for quite a long time. But, couldn't find any.

I have a table as below:

Month   Col_1   Col_2   Col_3   Col_4   Col_5   
---------------------------------------------
Jan     NULL    NULL    1       1       1   

I want to unpivot this table inorder to join with another table on fieldnames (Col_1,Col2,etc).

My query:

select Month,Name,value from 
TableName
    unpivot
    (
        Value 
        for Name in (Col_1,Col_2,Col_3,Col_4,Col_5)  
    ) u 

Current Result:

this gives me without the NULL values as below:

Month    Name    Value
-----------------------
Jan      Col_3   1
Jan      Col_4   1
Jan      Col_5   1

Expected Result:

I want the NULLs to be included in the result.

Month    Name    Value
-----------------------
Jan      Col_1   NULL
Jan      Col_2   NULL
Jan      Col_3   1
Jan      Col_4   1
Jan      Col_5   1

Any help would be appreciated.

like image 953
user2538559 Avatar asked May 28 '26 16:05

user2538559


1 Answers

SELECT name,value
FROM #Table1
CROSS APPLY (VALUES ('Col_1', Col_1),
                    ('Col_2', Col_2),
                    ('Col_3', Col_3),
                    ('Col_4', Col_4),
                    ('Col_5', Col_5)) 
            CrossApplied (name, value)

output

name    value
Col_1   NULL
Col_2   NULL
Col_3   1
Col_4   1
Col_5   1
like image 194
Chanukya Avatar answered May 30 '26 05:05

Chanukya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!