how to convert single line SQL result into multiple rows?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 17:33:15

问题


I am developing a T-SQL query in SSMS 2008 R2 which returns one line only. But the problem is that in this one line there are four fields which I instead want to be unique rows. For example, my output line looks like:

Col. 1   Col. 2   Col. 3   Col. 4
xxxx     yyyy     zzzz     aaaa

Instead, I want this to look like:

Question    Answer
Col. 1      xxxx
Col. 2      yyyy
Col. 3      zzzz
Col. 4      aaaa

I have tried using the UNPIVOT operator for this, but it is not doing the above. How can I achieve this?


回答1:


You should be able to use UNPIVOT for this:

Here is a static pivot where you hard code in the values of the columns:

create table t1
(
    col1 varchar(5),
    col2 varchar(5),
    col3 varchar(5),
    col4 varchar(5)
)

insert into t1 values ('xxxx', 'yyyy', 'zzzz', 'aaaa')

select question, answer
FROM t1
unpivot
(
    answer
    for question in (col1, col2, col3, col4)
) u

drop table t1

Here is a SQL Fiddle with a demo.

but you can also use a Dynamic Unpivot:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('t1') and
               C.name like 'Col%'
         for xml path('')), 1, 1, '')

set @query = 'SELECT question, answer
            from t1
            unpivot 
            (
               answer
               for question in (' + @cols + ')
            ) p '

execute(@query)



回答2:


This is from my data names but it is tested

select 'sID', sID as 'val' 
from [CSdemo01].[dbo].[docSVsys] 
where sID = 247   
union 
select 'sParID', sParID as 'val' 
from [CSdemo01].[dbo].[docSVsys] 
where sID = 247 ;

But UNPIVOT should work



来源:https://stackoverflow.com/questions/10822779/how-to-convert-single-line-sql-result-into-multiple-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!