我在使用SQL查询时遇到了一些麻烦。从表中我们称之为报告:
我想按名称列对所有报告进行分组。
然后,对于每个名称组,我想进入评级栏并计算评级为15或更低的次数。让我们说其中一个名为BOBBO的组发生了10次。
我还想知道提交评分的次数(与每个名字组的记录总数相同)。因此,使用名称组BOBBO,我们说他有20个评级。
因此,在这种情况下,BABBO集团50%的时间评级为15或更低。
我已经看过这些帖子 - 我仍然遇到一些问题。
using-count-and-return-percentage-against-sum-of-records
getting-two-counts-and-then-dividing-them
getting-a-percentage-from-mysql-with-a-group-by-condition-and-precision
divide-two-counts-from-one-select
阅读完之后,我尝试了这样的查询:
ActiveRecord::Base.connection.execute
("SELECT COUNT(*) Matched,
(select COUNT(rating) from reports group by name) Total,
CAST(COUNT(*) AS FLOAT)/CAST((SELECT COUNT(*) FROM reports group by name) AS FLOAT)*100 Percentage from reports
where rating <= 15 order by Percentage")
ActiveRecord::Base.connection.execute
("select name, sum(rating) / count(rating) as bad_rating
from reports group by name having bad_rating <= 15")
非常感谢任何帮助!
答案 0 :(得分:1)
考虑不良评级的条件聚合除以完整计数:
created_at
或者作为@CL。指出一个较短的条件聚合(逻辑表达式求和):
SELECT [name],
SUM(CASE WHEN [rating] <= 15 THEN 1 ELSE 0 END) / Count(*) AS bad_rating
FROM Reports
GROUP BY [name]