0

我试图将计数值除以子查询的值并乘以 100 以获得它的百分比。下面的代码有效......

SELECT data, rota as rt, COUNT(cliente_id) / 
(
 SELECT COUNT(DISTINCT cliente_id)
 FROM vw_grafico
 WHERE rota = rt  
) * 100 ) AS porcentagem

FROM vw_grafico
WHERE WEEKDAY(data)+1  = rota 
AND YEAR(data) = 2013
GROUP BY month(data)
ORDER BY data ASC

...但是,除此之外,我需要按月计算该值的平均值,这就是我的问题...当我尝试执行此操作时出现错误“无效使用组函数”:

SELECT data, rota as rt, AVG(COUNT(cliente_id) / 
(
 SELECT COUNT(DISTINCT cliente_id)
 FROM vw_grafico
 WHERE rota = rt  
) * 100 ) AS porcentagem

FROM vw_grafico
WHERE WEEKDAY(data)+1 = rota 
AND YEAR(data) = 2013
GROUP BY month(data)
ORDER BY data ASC

我应该怎么做才能解决这个错误?

4

1 回答 1

0
Select list fields( not aggregates) must be Subset of Group by List that in your query this is not true and your error is for that.

在您的查询中:

SELECT data, rota as rt, AVG(COUNT(cliente_id) / 
(
 SELECT COUNT(DISTINCT cliente_id)
 FROM vw_grafico
 WHERE rota = rt  
) * 100 ) AS porcentagem

FROM vw_grafico
WHERE WEEKDAY(data)+1 = rota 
AND YEAR(data) = 2013
GROUP BY month(data)
ORDER BY data ASC

选择列表是:

data, rota as rt

和组列表是:

month(data)

选择列表字段不是组列表的子集。所有选择列表字段必须在组列表中,例如:

SELECT month(data), rota as rt, AVG(COUNT(cliente_id) / 
(
 SELECT COUNT(DISTINCT cliente_id)
 FROM vw_grafico
 WHERE rota = rt  
) * 100 ) AS porcentagem

FROM vw_grafico
WHERE WEEKDAY(data)+1 = rota 
AND YEAR(data) = 2013
GROUP BY month(data), rota
ORDER BY data ASC
于 2013-05-03T18:52:33.993 回答