我当前的查询按预期返回每个种族群体中的总人数,例如:
Name | Count
----------------------
White | 22
Asian | 15
Black | 12
等。但是我想添加一个thrid列,它返回每个种族群体占总数的百分比,我将如何解决这个问题?
SELECT
eo.EthnicOriginName,
ISNULL(e.Number, '')
--CAST(e.Number AS FLOAT) / CAST(COUNT(e.intEthnicOriginID) AS FLOAT) * 100
FROM
tblEthnicOrigin eo
INNER JOIN tblPerson p ON p.intEthnicOriginID = eo.EthnicOriginID
LEFT JOIN (SELECT intEthnicOriginID, COUNT(p.intPersonID) [Number]
FROM tblPerson p
INNER JOIN tblClient c on c.intPersonID = p.intPersonID
GROUP BY intEthnicOriginID) e on e.intEthnicOriginID = eo.EthnicOriginID
GROUP BY
eo.EthnicOriginName, e.Number
答案 0 :(得分:2)
在大多数数据库中,您将使用ANSI标准窗口函数:
SELECT eo.EthnicOriginName, COUNT(*) as num,
COUNT(*) * 1.0 / SUM(COUNT(*)) OVER () as ratio
FROM tblEthnicOrigin eo INNER JOIN
tblPerson p
ON p.intEthnicOriginID = eo.EthnicOriginID
GROUP BY eo.EthnicOriginName;
* 1.0
只是因为某些数据库进行整数除法,我们不希望整数除法。