两个动态列上的SQL Pivot

时间:2018-05-07 13:36:23

标签: sql sql-server pivot pivot-table

我知道堆栈溢出时有很多PIVOT两列,但似乎没有一个符合我的需求:(

这是我的表格: enter image description here

我想把它转到这个: enter image description here

这是最初的设置:

CREATE TABLE TblPivot
(ID         INT IDENTITY(1, 1),
 Shop    VARCHAR(MAX),
 ElementId  VARCHAR(10),
 QuestionId VARCHAR(10),
 [Value]    VARCHAR(20)
);

GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem10','question1','one')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem11','question1','two')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem20','question2','1')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem20','question3','p1')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem21','question2','2')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem21','question3','p2')

我怀疑它一定是CROSS-APPLY和PIVOT的东西,但我不确定如何解决这个问题。

PS:元素ID可以为null

谢谢!

1 个答案:

答案 0 :(得分:1)

执行条件聚合:

select Shop,
       max(case when (QuestionId = 'question1' and ElementId = 'elem10')
                then value end) [question1- elem10],
       . . .
from TblPivot p
where QuestionId in ('question1', 'question2', 'question3') and
      ElementId in ('elem10', 'elem11', 'elem20', 'elem21')
group by Shop;