另一道很有挑战性的SQL语句,想了好久没想到好的办法
userid questionid answer
2021187 1 A
2021187 2 B
2021187 3 F
2021187 4 B
2021187 5 B
2021187 6 A
2026080 1 A
2026080 2 A
2026080 3 E
2026080 4 A
2026080 5 B
2026080 6 B
2031349 1 B
2031349 2 B
2031349 3 K
2031349 4 A
2031349 5 D
2031349 6 A
转成以下方式输出:
userid question1 question2 question3 question4 question5 question6
2021187 A B F B B A
2026080 A A E A B B
2031349 B B K A D A
------解决方案--------------------userid questionid answer
2021187 1 A
2021187 2 B
2021187 3 F
2021187 4 B
2021187 5 B
2021187 6 A
select userid ,
max(case when questionid = 1 then answer end) question1,
max(case when questionid = 2 then answer end) question2,
max(case when questionid = 3 then answer end) question3,
max(case when questionid = 4 then answer end) question4,
max(case when questionid = 5 then answer end) question5,
max(case when questionid = 6 then answer end) question6
from tb
group by userid
------解决方案--------------------declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+ ',[question '+rtrim(questionid)+ ']=max(case questionid when '+rtrim(questionid)+ ' then answer end) '
from (select distinct questionid from 表) t
set @sql= 'select userid '+@sql+ ' from 表 group by userid '
exec(@sql)
------解决方案--------------------create table ta(userid int, questionid int ,answer varchar(5))
insert ta select 2021187, 1, 'A '
insert ta select 2021187, 2, 'B '
insert ta select 2021187, 3, 'F '
insert ta select 2021187, 4, 'B '
insert ta select 2021187, 5, 'B '
insert ta select 2021187, 6, 'A '
insert ta select 2026080, 1, 'A '
insert ta select 2026080, 2, 'A '
insert ta select 2026080, 3, 'E '
insert ta select 2026080, 4, 'A '
insert ta select 2026080, 5, 'B '
insert ta select 2026080, 6, 'B '
insert ta select 2031349, 1, 'B '
insert ta select 2031349, 2, 'B '
insert ta select 2031349, 3, 'K '
insert ta select 2031349, 4, 'A '
insert ta select 2031349, 5, 'D '