2012-12-07 87 views
0

我有一張可能如下所示的數據表。答案總是以用戶的6個塊的形式提交。如果有人爲questionID 1回答「1」,那麼我需要知道他們爲question4回答了什麼,或者如果他們對問題2回答1,那麼我需要他們回答問題5,如果他們回答1回答問題3,我需要他們的回答回答問題6.根據另一行的內容從其他行獲取數據

user questionID response 
1  1    2 
1  2    3 
1  3    1 
1  4    5 
1  5    5 
1  6    2 
2  1    1 
2  2    6 
2  3    3 
2  4    3 
2  5    2 
2  6    5 

我真的可以做一些這方面的幫助。非常感謝

+0

使用'CASE'...你關心對問題4,5或6的回答嗎? – Kermit

+0

4,5和6與問題1,2和3有關,所以如果我的標準是對問題1,2或3的回答1,那麼我需要問題4,5或6的相關回答。那是在任何方式清楚?這很難解釋! – Dave

+0

如果用戶在第1,第2和第3中未回答1,您需要什麼? – HugoLemos

回答

0

是您需要的嗎?嘗試運行此查詢。

select u1.*, u2.response from users u1 
left join users u2 
on u1.user = u2.user and u1.questionID = u2.questionID - 3 
where u1.response = 1 

子( 'INP1' FROM 4)給出1:

select u1.*, u2.response from users u1 
left join users u2 
on u1.user = u2.user and 
    substring(u1.questionID FROM 4) = substring(u2.questionID FROM 4) - 3 
where u1.response = 1 
+0

我認爲這正是我所需要的,非常感謝你!我只是在where子句中添加一點,以便僅查詢問題1,2或3. – Dave

+0

Aaargh!我剛剛發現questionID不是一個整數,但事實上它是一個值爲inp1,inp2,inp3,inp4,inp5,inp6的字符串。有沒有辦法修改你的問題? – Dave

+0

如果questionID是像'inp1'這樣的字符串,那麼你只需要從那裏得到數字。你可以用SUBSTRING函數來完成。我添加了新的查詢,試試吧。 – amk

0

我想你想 「轉動」,在這裏你會得到所有的答案在一起:

select 
    t1.response as response1, 
    t2.response as response2, 
    t3.response as response3, 
    t4.response as response4, 
    t5.response as response5, 
    t6.response as response6 
from mytable t1 
left join mytable t2 on t1.user = t2.user and t2.questionId = 2 
left join mytable t3 on t1.user = t3.user and t3.questionId = 3 
left join mytable t4 on t1.user = t4.user and t4.questionId = 4 
left join mytable t5 on t1.user = t5.user and t5.questionId = 5 
left join mytable t6 on t1.user = t6.user and t6.questionId = 6 
where t1.user = ? 

我會使這個視圖,並添加t1.user作爲一列,那麼你可以選擇從視圖wh用戶=?。