2010-11-05 144 views
2

即時通訊相當確定我可以使用PIVOT功能來解決我的問題,但我無法弄清楚。任何援助將不勝感激。SQL Server PIVOT

,所以我必須看起來像

create table Answer (
id int, 
question_id int, 
user_id int, 
answer varchar(1025)) 

一個表,我想編寫一個返回結果在下面設置查詢:

 
user_id, question_1, question_2, question_3 
1,  'answer1', 'answer2', 'answer3' 
2,  'answer1', 'answer2', 'answer3' 
n,  'answer1', 'answer2', 'answer3' 

是這甚至可能嗎?

TIA

回答

1

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 
+0

awsome謝謝你的答案 - 正是我在找 – 2010-11-05 15:43:52

+0

不客氣。如果你想知道更多的PIVOT,請參閱我的其他答案。這是一個有用的功能,但有一些你知道的事情。 – Claudia 2010-11-05 16:09:31

-1

可能嗎?是。

可取嗎?很少會遇到很多性能問題,完全是在sql中完成的。一旦關鍵數據列的數量超過了8左右,性能就完全消失了。

這是否帶有法律問題?不幸的是,是的。微軟以其無限的智慧獲得了專利「method and system for mapping between logical data and physical data」,2007年7月發佈

因此,請謹慎行事。

+1

我不知道如何誇大其詞關於微軟的法律行爲與這個問題有關。 – 2010-11-05 15:29:04

+0

@Randolph:我抨擊了專利。不過,我覺得讀這本書的人應該意識到基於這種動態數據實現的非常現實的潛在噩夢。 – NotMe 2010-11-05 15:35:50