Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a question about in SQL Server: how to combine 4 columns into 1 column in a query.

Table: emp

empid | addr | sal | doj
------+------+-----+------------
  1   | hyd  | 10  | 10-01-1990
  2   | del  | 20  | 12-03-1999
  1   | pune | 50  | 12-03-2017

Based on above data I want output like below

empid | empvalues
------+---------------
1     | hyd
1     | 10
1     | 10-01-1990
2     | del
2     | 20
2     | 12-03-1999
1     | pune
1     | 50
1     | 12-03-2017

I tried with a query like this:

select 
    empid, cast (addr as varchar(100)) as empvalues 
from emp

union all

select empid, cast (sal as varchar(100)) as empvalues 
from emp

union all

select empid, cast (doj as varchar(100)) as empvalues 
from emp

This query is returning the correct result, but it takes a lot of time due to calling same table 3 times.

Can you please tell me how to write any alternative query to achieve this task in SQL Server?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
191 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could try using UNPIVOT, like this...

SELECT empid, empvalues
FROM (
    select empid, addr, convert(varchar(100), sal) as sal,  convert(varchar(100), doj, 103) as doj
    from emp
) pv
UNPIVOT
(
    empvalues
    FOR ev in (addr, sal, doj)
) AS ev

produces this output...

sql results

Resources for your reference...

https://codingsight.com/understanding-pivot-unpivot-and-reverse-pivot-statements/ https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...