如何在SQL中以列的形式转换表行

时间:2015-02-25 05:32:29

标签: sql sql-server-2008

您好我有两个表,我想生成报告,其中所有行都是单行。

tbl_Questions

Id  Name
---------
1   Abc
2   Cde
3   xyz
4   MMM

tbl_Reponses

Id  QuestionId   Values
------------------------
1      1           123
2      2           456
3      3           444

现在我想得到一个查询,它会在结果中显示这样的时间。

Id Abc Cde xyz MMM
-------------------
1  123 456 444 

如何通过查询获得此信息?

2 个答案:

答案 0 :(得分:0)

使用PIVOT执行此操作:

SELECT ROW_NUMBER() OVER(ORDER BY [Abc])Id,* FROM
(
SELECT Name,Value FROM tbl_Questions A LEFT JOIN tbl_Reponses B ON A.Id=B.Id
) AS tbl
PIVOT(SUM(Value) FOR Name IN([Abc],[Cde],[xyz],[MMM]))AS pvt

CrossTab方法

SELECT
    ROW_NUMBER() OVER (ORDER BY MAX(A.Id))Id,
    [Abc] = MAX(CASE WHEN Name = 'Abc' THEN Value END),
    [Cde] = MAX(CASE WHEN Name = 'Cde' THEN Value END),
    [xyz] = MAX(CASE WHEN Name = 'xyz' THEN Value END),
    [MMM] = MAX(CASE WHEN Name = 'xyz' THEN Value END)
FROM tbl_Questions A LEFT JOIN tbl_Reponses B ON A.Id=B.Id

答案 1 :(得分:0)

使用分组

select 
ID
, MIN(CASE WHEN A.NAME ='ABC'
THEN B.VALUES
END) ABC
, MIN(CASE WHEN A.NAME ='cde'
THEN B.VALUES
END) cde
, MIN(CASE WHEN A.NAME ='xyz'
THEN B.VALUES
END) xyz
, ISNULL(MIN(CASE WHEN A.NAME ='mmm'
THEN B.VALUES
END),'') mmm
FROM
tbl_Questions A
inner join tbl_Reponses B
on A.ID=B.ID
group by A.ID