例如,如果我想在“员工”表中列出男性和女性的百分比。这是正确的吗?
SELECT Sex, COUNT (Sex) AS [%]
FROM Employees
GROUP BY Sex;
如果我想列出低于 50% 的性别怎么办?以下是正确的吗?
SELECT Sex, COUNT (Sex) AS [%]
FROM Employees
GROUP BY Sex
HAVING COUNT (Sex) < 50%
谢谢你。
例如,如果我想在“员工”表中列出男性和女性的百分比。这是正确的吗?
SELECT Sex, COUNT (Sex) AS [%]
FROM Employees
GROUP BY Sex;
如果我想列出低于 50% 的性别怎么办?以下是正确的吗?
SELECT Sex, COUNT (Sex) AS [%]
FROM Employees
GROUP BY Sex
HAVING COUNT (Sex) < 50%
谢谢你。
我相信这就是你要找的。
SELECT Sex, (Count(Sex)* 100 / (SELECT Count(*) FROM Employees)) as MyPercentage
FROM Employees
GROUP BY Sex
然后你可以做
HAVING MyPercentage < 50
不,大多数 SQL 版本都支持窗口函数。您可以使用以下方法计算百分比:
SELECT Sex, COUNT(Sex)/(sum(count(sex)) over ()) AS [%]
FROM Employees
GROUP BY Sex;
(我省略了100*
,因为我不确定您是否想要 0 到 100 之间的百分比或 0 到 1 之间的概率。)
某些版本的 SQL 会进行整数除法,在这种情况下,您需要将其转换为小数或浮点数:
SELECT Sex, cast(COUNT(Sex) as float)/(sum(count(sex)) over ()) AS [%]
FROM Employees
GROUP BY Sex;