简体   繁体   English

Sql count查询始终返回1

[英]Sql count query always return 1

I'm using this query to find out the percentage of female employees. 我正在使用此查询来查找女性员工的百分比。 But somehow, when I combine that operation in one query like the one below, it always returns 1.0. 但不知何故,当我在一个查询中组合该操作时,如下所示,它总是返回1.0。

However, if I query separately and divide it, it's proper. 但是,如果我单独查询并除以它,那是正确的。 I think I'm messing up with some syntax here. 我想我在这里弄乱了一些语法。

What am I doing wrong? 我究竟做错了什么?

employees and citizens are two tables. employeescitizens是两张桌子。

SELECT (count(e.name)/count(c.name))
from citizens as c, employees as e
where c.gender=false and e.gender=false

You're simply creating a cross product between the rows in the two tables, and then counting the number of rows in the resulting cross product. 您只是在两个表中的行之间创建交叉产品,然后计算生成的交叉产品中的行数。 You need to use separate queries to calculate each count: 您需要使用单独的查询来计算每个计数:

SELECT (SELECT COUNT(*) FROM employees WHERE gender = false)/
       (SELECT COUNT(*) FROM citizens WHERE gender = false)

You're getting 1 because count returns integers.You need to cast them to floats so that you can get percentage. 你得到1因为count返回整数。你需要将它们转换成浮点数,这样你才能得到百分比。 Also, only casting the numerator is enough in this case.This will return quotient in floats. 此外,在这种情况下,只输出分子就足够了。这将返回浮点数中的商。

SELECT cast(count(e.name)as float)/count(c.name)
from citizens as c, employees as e
where c.gender=false and e.gender=false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM