样本记录:
examid setcode answer
------- -------- --------
10 A A
10 A B
10 A X
10 B A
10 B B
10 B C
我试图通过setcode找到计数组,其中答案是X. 我尝试了以下查询:
SELECT setCode,COUNT(answer) FROM mcq_answer WHERE examid=10 AND answer='X' GROUP BY setCode
这个结果返回以下结果:
setcode count
------- --------
A 1
但我正在寻找以下内容:
setcode count
------- --------
A 1
B 0
Setcode在这里是动态的。我只提到过A和B.可能有更多的setocdes如C,D,E,F等。我该怎么做。我正在使用MySQL
答案 0 :(得分:1)
您可以使用以下查询
SELECT C.setCode ,
SUM(CASE WHEN B.setcode IS NULL THEN 0
ELSE 1
END) AS answer
FROM ( SELECT A.setCode ,
COUNT(1) AS cnt
FROM mcq_answer A
GROUP BY A.setCode
) C
LEFT JOIN mcq_answer b ON C.setcode = B.setcode
AND B.answer = 'X'
GROUP BY C.setCode
答案 1 :(得分:0)
您可以使用SUM + IF
获得此结果:
SELECT `setCode`, SUM(if (`answer`='X', 1,0)) as answer
FROM `mcq_answer`
WHERE examid=10
GROUP BY `setcode`
答案 2 :(得分:0)
尝试:
SELECT A.setcode,
COUNT(CASE WHEN B.answer ='X' THEN B.answer ELSE NULL END) as count_x
FROM
(SELECT DISTINCT setcode FROM YOUR_TABLE) A
LEFT JOIN
YOUR_TABLE B
ON A.setcode = B.setcode
GROUP BY A.setcode;
它也适用于setcode
的动态值集。