select A.QueId,Question,Answer from
ServayQues1 as S inner join ServayQuesAns1 as A
on S.QueId=A.QueId
QueId | Question | Answer
----------------------------
1 test Ok
1 test not bad
1 test need to be improve
----------------------------
我的预期输出低于
QueId | Question | answer1 | answer2 | answer3
--------------------------------------------------------------------------
1 test Ok not bad need to be improve
---------------------------------------------------------------------------
如何获得此输出?
答案 0 :(得分:0)
希望这就是你所需要的。
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders = COALESCE(
@PivotColumnHeaders + ',[' + cast([answer] as varchar) + ']',
'[' + cast([answer] as varchar)+ ']')
FROM (SELECT DISTINCT Answer from
ServayQues1 as S inner join ServayQuesAns1 as A
on S.QueId=A.QueId) s
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
SELECT *
FROM
(
SELECT A.QueId,Question,Answer
FROM ServayQuesAns1 A inner join
ServayQues1 q on q.QueId= a.QueId
) AS source
PIVOT
(
MAX([Answer])
FOR [Answer] IN (
' + @PivotColumnHeaders + '
)
) AS PivotTable
'
print @PivotTableSQL
EXECUTE(@PivotTableSQL)