如何在mysql中选择记录数与具有相同字段值的记录数之间的比率?

时间:2018-10-12 21:52:08

标签: mysql select

假设我在mysql数据库中有一个表

(id,idWord,isCorrect)
------------------
('1','1', '0'),
('2','1', '1'),
('3','1', '1'),
('4','1', '1'),
('5','1', '0'),
('6','1', '1'),

('7','2', '0'),
('8','2', '0'),
('9','2', '1'),
('10','2', '1')

如何选择具有isCorrect = 1的记录数与具有相同idWord的记录总数之间的比率?在这种情况下会导致

('1','0.6')     (-> 4/6)
('2','0.5')     (-> 2/4)

我尝试过

 SELECT 
  (SELECT COUNT(`isCorrect`) FROM `wordstyped` GROUP BY `idWord`,`isCorrect`) 
  / 
  (SELECT COUNT(`isCorrect`) FROM `wordstyped` GROUP BY `idWord`,`isCorrect` WHERE `isCorrect`=1)

但它不起作用。

http://www.sqlfiddle.com/#!9/f36c58/1

2 个答案:

答案 0 :(得分:3)

使用SELECT作为值时,它仅返回一行,因此无法返回所有分组的行。您可以使用单个查询来汇总多个内容。

SELECT idWord, SUM(isCorrect = 1) / COUNT(*) AS ratio
FROM `wordstyped`
GROUP BY idWord

类似isCorrect = 1的比较表达式为true时为1,为false时为0,因此将它们相加即可计算条件为true的行数。

您还可以使用AVG()函数,因为平均值只是总数除以计数。

SELECT idWord, AVG(isCorrect = 1) AS ratio
FROM `wordstyped`
GROUP BY idWord

答案 1 :(得分:2)

尝试这个:

SELECT
    idWord,
    SUM(CASE WHEN isCorrect = 1 THEN 1 ELSE 0 END) AS corrects,
    COUNT(*) AS total,
    SUM(CASE WHEN isCorrect = 1 THEN 1 ELSE 0 END) / COUNT(*) AS ratio
FROM
    wordstyped
GROUP BY
    idWord