SQL选择一个正确选择的问题

时间:2014-08-29 17:54:25

标签: sql sql-server

我有一个问题表:

QuestionID    QuestionText
----------------------------------
1             How tall is Imhotep?
2             How many times can Queen Elizabeth V's dress change before it overheats?

还有一个QuestionChoice表:

ChoiceID    QuestionID    ChoiceText                 Correct
------------------------------------------------------------
1           1             Imhotep is invisible       1
2           1             30'                        0
3           1             6'4"                       0
4           1             I don't know               0
5           2             342                        0
6           2             Infinity                   0
7           2             MATHS                      0
8           2             The party was cancelled    0

正如您所看到的,一些数据已经变坏(选择8应该是正确的)。我想只选择一个正确选择的问题。例如,在这种情况下,我想选择问题1而不是问题2.

这是我尝试的但它不起作用:

select q.questionid
from question q
    join questionchoice qc on q.questionid = qc.questionid
group by q.questionid
having count (qc.correct) = 1

1 个答案:

答案 0 :(得分:3)

替换

having count (qc.correct) = 1

having sum (case when qc.correct = 1 then 1 else 0 end) = 1