0

我有一个数据表,可能如下所示。用户总是以 6 个块的形式提交答案。如果有人对问题 ID 1 回答了“1”,那么我需要知道他们对问题 4 的回答是什么,或者如果他们对问题 2 回答了 1,那么我需要他们对问题 5 的回答,如果他们对问题 3 回答了 1,我需要他们的回答问题 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

我真的可以在这方面提供一些帮助。非常感谢

4

2 回答 2

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

substring('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
于 2012-12-07T20:52:54.593 回答
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为列,然后您可以从 user = ? 的视图中选择。

于 2012-12-07T20:58:01.583 回答