2012-12-07 93 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用户=?。