我知道堆栈溢出时有很多PIVOT两列,但似乎没有一个符合我的需求:(
这是最初的设置:
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
谢谢!
答案 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;