如何将单行SQL结果转换为多行?
问题描述:
我正在 SSMS 2008 R2 中开发一个仅返回一行的 T-SQL 查询.但问题是在这一行中有四个字段,我希望它们是唯一的行.例如,我的输出行如下所示:
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
我已尝试为此使用 UNPIVOT 运算符,但它没有执行上述操作.我怎样才能做到这一点?
I have tried using the UNPIVOT operator for this, but it is not doing the above. How can I achieve 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
这是带有演示的 SQL Fiddle.
但您也可以使用动态逆枢轴:
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)