在mysql中除以计数结果

时间:2014-01-21 22:32:22

标签: mysql count divide

SELECT COUNT(*) FROM Table1 WHERE user = "carl" AND ans = "yes"

然后我想将此查询的输出除以另一个查询,例如输出为10.所以它将如下:

10 / SELECT COUNT(*) From Table1 WHERE user = "carl"

如何正确的语法?

谢谢

3 个答案:

答案 0 :(得分:14)

您想要使用条件聚合和除法。您不需要两个查询:

SELECT SUM(ans = 'yes')/COUNT(*)
FROM Table1
WHERE user = 'carl';

SUM(ans = 'yes')计算yes的行数。实际上,您可以进一步简化为:

SELECT avg(ans = 'yes')
FROM Table1
WHERE user = 'carl';

答案 1 :(得分:2)

您可以通过将两个查询作为子查询运行来执行此操作:

SELECT 
  (SELECT COUNT(*) FROM Table1 WHERE user = "carl" AND ans = "yes") / 
  (SELECT COUNT(*) From Table1 WHERE user = "carl")

答案 2 :(得分:1)

做一个

SELECT (10/COUNT(*)) AS `myVariable` FROM `Table1` WHERE...

然后根据需要使用myVariable