0

我有一个包含“系统”和“颜色代码”字段的表(详细信息)。我想通过 color_code 计算每个系统的项目百分比,每个系统都有一个 SQL 语句。我有这个:

SELECT system, color_code, Count(color_code) AS ColorCount, 
       Count(color_code)*100 /(select count(*) from Detail) AS ColorPercent
FROM Detail
GROUP BY system, color_code;

“ColorPercent”中的结果是所有记录的结果。我希望“ColorPercent”基于每个“系统”的记录数。

我试过这个(将“GROUP BY system”添加到表达式中),但它不起作用,

SELECT system, color_code, Count(color_code) AS ColorCount, 
       Count(color_code)*100/(select count(*) from Detail 
                              GROUP BY system) AS ColorPercent
FROM Detail
GROUP BY system, color_code;
4

3 回答 3

1

怎么样:

 SELECT system, color_code, 
        Count(color_code) AS ColorCount, 
        Count(color_code)*100/(select count(*) from Detail d 
                               where d.system=detail.system) AS ColorPercent
FROM Detail
GROUP BY system, color_code;
于 2012-09-05T14:49:56.720 回答
1

可能不起作用,因为您的子查询返回多个值。尝试添加 where 子句,以确保使用唯一的系统并获取计数

SELECT system, color_code, Count(color_code) AS ColorCount, 
Count(color_code)*100/(select count(*) from Detail where system = D.system) AS ColorPercent
FROM Detail D
GROUP BY system, color_code;

这应该有效。如您所见,我正在根据主要查询中的组关联计数

于 2012-09-05T14:50:06.277 回答
1

您需要限制在子查询中获得的记录。尝试:

SELECT system, color_code, Count(color_code) AS ColorCount, Count(color_code)*100 /(select count(*) from Detail where system = D.system) AS ColorPercent
FROM Detail D
GROUP BY system, color_code;

我不确定你是否需要给你的表起别名

于 2012-09-05T14:51:08.443 回答