Assumming在表中該輸入:
insert into answer SELECT 1, 1, 123, 'Answer ZZZZ'
insert into answer SELECT 2, 2, 123, 'Answer AAAA'
insert into answer SELECT 3, 3, 123, 'Answer BBBB'
insert into answer SELECT 4, 1, 345, 'Answer CCCC'
insert into answer SELECT 5, 2, 345, 'Answer DDDD'
insert into answer SELECT 6, 1, 678, 'Answer EEEE'
insert into answer SELECT 7, 2, 678, 'Answer FFFF'
insert into answer SELECT 8, 3, 678, 'Answer SSSS'
insert into answer SELECT 9, 3, 999, 'Answer RRRR'
你可以做這樣的事情:
SELECT user_id, [1] as Answer1, [2] as Answer2, [3] as Answer3
FROM (
SELECT question_id, user_id, answer
FROM answer) P
PIVOT
(
MAX (answer)
FOR Question_id IN ([1], [2], [3])
) AS pvt
你得到這樣的結果:
user_id Answer1 Answer2 Answer3
123 Answer 1 Answer AAAA Answer BBBB
345 Answer CCCC Answer DDDD NULL
678 Answer EEEE Answer FFFF Answer SSSS
999 NULL NULL Answer RRRR
awsome謝謝你的答案 - 正是我在找 – 2010-11-05 15:43:52
不客氣。如果你想知道更多的PIVOT,請參閱我的其他答案。這是一個有用的功能,但有一些你知道的事情。 – Claudia 2010-11-05 16:09:31