例如,如果我想在“员工”表中列出男性和女性的百分比。 这是对的吗?
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%
谢谢。
答案 0 :(得分:2)
我相信这就是你要找的东西。
SELECT Sex, (Count(Sex)* 100 / (SELECT Count(*) FROM Employees)) as MyPercentage
FROM Employees
GROUP BY Sex
然后你可以做
HAVING MyPercentage < 50
答案 1 :(得分:1)
没有。大多数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;