在SQL查询中计算内联百分比

时间:2011-05-30 09:13:37

标签: sql ms-access

SELECT User, COUNT(*) as count FROM Tests WHERE Release = '1.0' GROUP by User;

以上查询将返回不同的数字,但是,我想将计数转换为与总记录数相关的百分数。考虑WHERE子句的记录总数。

3 个答案:

答案 0 :(得分:2)

SELECT R1.user, COUNT(*)/R2.COUNT_ALL AS Expr1
  FROM Releases R1,
       (SELECT COUNT(*) As COUNT_ALL FROM Releases WHERE Release = '1.0') R2
 WHERE R1.Release = '1.0'
 GROUP BY R1.user, R2.COUNT_ALL

答案 1 :(得分:1)

这是使用单个SELECT的另一种方法:

SELECT 
    Tests.User, 
    Count(IIf([Tests].[Release]='1.0', 1, Null)) / Count(*) AS Percentage
FROM 
    Tests
GROUP BY 
    Tests.User

与之前建议的方法不同,无论是好还是坏,这个方法都会为测试中没有记录的用户返回记录,其中Release为“1.0”。如果您不想要这些记录,可以添加一个HAVING子句来消除它们。

希望这有帮助。

答案 2 :(得分:-2)

与Brian的答案相似,但仅限于标准SQL而不是MS Access。 (也可以COUNT使用SUM代替NULL0 SELECT Tests.User, Sum(CASE WHEN Release='1.0' THEN 1 ELSE 0 END) / Count(*) AS Percentage FROM Tests GROUP BY Tests.User 。{/ p>

{{1}}