Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

How to write dynamic query columns into rows in SQL Server?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...