仅返回具有多个正确选择的结果

时间:2012-12-13 19:35:59

标签: sql sql-server having

我需要提出一个查询,以显示哪些问题有多个正确答案。一直在寻找,找不到我需要的东西。我找到了这个,这有点像我想要的,但它对我不起作用,也许我做错了。

SQL Count where clause

这是我到目前为止所拥有的......

SELECT pq.ItemID, pq.RevNum, pc.sequence, pc.correct FROM Choice pc 
JOIN Question pq on pc.UniqueQID = pq.UniqueQID and pc.RevNum = pq.RevNum
Group BY pq.ItemID, pq.RevNum, pc.Sequence, pc.Correct
ORDER BY ItemID, RevNum, Sequence

这将返回每个问题/修订的列表以及所有选项。结果看起来像这样......

ItemID      RevNum  Seq     Correct
12776   1   A   0
12776   1   B   0
12776   1   C   1

12777   1   A   0
12777   1   B   1
12777   1   C   0
12777   1   D   0

12778   1   A   1
12778   1   B   1
12778   1   C   0
12778   1   D   1

8301    3   a   1
8301    3   b   2
8301    3   c   2
8301    3   d   2

8303    3   a   2
8303    3   b   1
8303    3   c   2
8303    3   d   2

为了清晰起见,我添加了新行。选择= 1正确,0或2不正确。我只需要有多个正确答案的问题,例如上面的12778。

基于上面的链接文章,我尝试了类似这样的东西,但它没有用,说错误在第4行附近=。

SELECT pq.ItemID, pq.RevNum, pc.sequence, pc.correct FROM pubChoice pc 
JOIN pubQuestion pq on pc.UniqueQID = pq.UniqueQID and pc.RevNum = pq.RevNum
Group BY pq.ItemID, pq.RevNum, pc.Sequence, pc.Correct
HAVING Count(correct=1) > 1
ORDER BY ItemID, RevNum, Sequence

3 个答案:

答案 0 :(得分:2)

您只需要正确值为1的记录,因此请将其添加到where子句中。在其他组之后,添加一个count(*),因此你可以在该计数(*)上有一个having子句。 这样的事情应该有效:

SELECT pq.ItemID, pq.RevNum, pc.sequence,count(*) FROM pubChoice pc 
JOIN pubQuestion pq on pc.UniqueQID = pq.UniqueQID and pc.RevNum = pq.RevNum
WHERE pc.Correct = 1
Group BY pq.ItemID, pq.RevNum, pc.Sequence
HAVING Count(*) > 1
ORDER BY ItemID, RevNum, Sequence

答案 1 :(得分:0)

您如何确定选择是否正确?你需要这样的东西:

SELECT pq.*
FROM Question pq
INNER JOIN 
(
SELECT ItemID, COUNT(*) as correctCount
FROM Question q
INNER JOIN Choice c
ON c.UniqueQID = q.UniqueQID 
WHERE ANSWER_IS_CORRECT
GROUP BY ItemID
HAVING COUNT(*) > 1
) mults
ON pq.ItemID = mults.ItemID

请注意,我没有对此进行过测试,但只要您有办法判断某个选项是否正确,理论上它应该可以正常工作。它将返回具有多个正确答案的所有ItemID,然后返回到ItemID上的问题以获取其上的所有选项(您可能需要联接回选择)。

答案 2 :(得分:0)

根据您的评论和最初的问题,看起来这对您有用:

SELECT pq.ItemID, 
  pq.RevNum, 
  pc.sequence, 
  pc.correct 
FROM Choice pc 
JOIN Question pq 
  on pc.UniqueQID = pq.UniqueQID 
  and pc.RevNum = pq.RevNum
where exists (select count(*) TotalCorrect, UniqueQID, RevNum
              from choice c
              where correct = 1
                and pc.UniqueQID = c.UniqueQID
                and pc.RevNum = c.RevNum
              group by UniqueQID, RevNum
              having count(*) > 1);

请参阅SQL Fiddle with Demo

结果是:

| ITEMID | REVNUM | SEQUENCE | CORRECT |
----------------------------------------
|  12778 |      1 |        A |       1 |
|  12778 |      1 |        B |       1 |
|  12778 |      1 |        C |       0 |
|  12778 |      1 |        D |       1 |