我有三张桌子。 SurveyFact,问题和回应。调查事实包含客户调查的数据,而问题和答复表有明显的数据,问题列表和每个问题的可能答案。
SurveyFact:
| SurveyFactID | ClientID | QuestionID | ResponseCode |
------------------------------------------------------------
| 1 | 1 | 1 | 3 |
| 2 | 1 | 2 | 3 |
| 3 | 1 | 3 | 1 |
问题:
| QuestionID| QuestionText |
-------------------------------------
| 1 | blah blah blah |
| 2 | blah blah blah |
| 3 | blah blah blah |
响应:
| ResponseID| QuestionID | ResponseCode |ResponseText |
-----------------------------------------------------------|
| 1 | 1 | 1 | like |
| 2 | 1 | 2 | don't care |
| 3 | 1 | 3 | hate |
| 4 | 2 | 1 | like |
| 5 | 2 | 2 | don't care |
| 6 | 2 | 3 | hate |
这是我提出的查询。 (那失败了)
select
sf.QuestionCode as [Question Number],
q.QuestionText as [Question Text],
r.ResponseText as [Reponse]
from SurveyFact sf
inner join Question q
on q.QuestionID = sf.QuestionID
inner join Responses r
on r.ResponseCode = sf.ResponseCode
where sf.ClientID = '1'
and sf.QuestionID = q.QuestionID
and sf.ResponseCode = r.ResponseCode
即使我使用select distinct,它也会向我提供每个可能答案的调查和问题,而不仅仅是SurveyFact中列出的问题/答案组合。
请帮忙吗?
请求表: 我在看什么
| Question Number | Question Text |Response Text |
------------------------------------------------------
| 1 | blah blah blah | like |
| 1 | blah blah blah | don't care |
| 1 | blah blah blah | hate |
| 2 | blah blah blah | like |
| 2 | blah blah blah | don't care |
| 2 | blah blah blah | hate |
我想要的是什么:
| Question Number | Question Text |Response Text |
------------------------------------------------------
| 1 | blah blah blah | don't care |
| 2 | blah blah blah | like |
首先是Number,QUestion,然后是每个可能的答案。第二个是数字,问题,刚选择的答案
答案 0 :(得分:1)
select
sf.QuestionID as QuestionNumber,
q.QuestionText as QuestionText,
r.ResponseText as Reponse
from SurveyFact sf, Question q, Response r
where sf.ClientID = '1'
and
sf.QuestionID = q.QuestionID
and
r.QuestionID = q.QuestionID
and
sf.ResponseCode = r.ResponseCode
我认为你正在寻找。
结果将是:
| Question Number | Question Text |Response Text |
------------------------------------------------------
| 1 | blah blah (q1) | hate |
| 2 | blah blah (q2) | hate |
在你的结果中写道:
| Question Number | Question Text |Response Text |
------------------------------------------------------
| 1 | blah blah blah | don't care |
| 2 | blah blah blah | like |
但我看不出应该如何“不关心”和“喜欢”? 他们有ResponseCode 1和2。 并且ResultCode 1和2不在SurveyFact中。 井1是,但它适用于问题3,问题3不在响应表中。
答案 1 :(得分:0)
添加一个条件,响应必须是正确的问题:
inner join Responses r
on r.ResponseCode = sf.ResponseCode
and r.QuestionID = q.QuestionID