[英]How to get percentage of a column in top 20 SQL?
I am trying to find percentage of pageType is having rating lesser than 20. 我试图找到pageType的评分低于20的百分比。
My Table looks like : 我的桌子看起来像:
requestId rank pageType
MMCVS 0 HOME
MMCVS 1 MOBILE
MMCVS 2 HOME
BBVSS 0 HOME
BBVSS 11 MOBILE
BBVSS 12 HOME
so far, I tried : 到目前为止,我尝试了:
select pageType, Top20, Top20/count(DISTINCT requestId) as Percentage
from (
SELECT
pageType, requestId,
SUM(CASE WHEN rank <= 20 THEN 1 ELSE 0 END) as Top20
FROM
tempTable
group by pageType, requestId) tempTable group by pageType
But getting error : 但是出现错误:
expression 'Top20' is neither present in the group by, nor is it an aggregate function.
Yes you need to add any non-aggregated fields into group by fields list. 是的,您需要将任何未聚合的字段添加到“按字段分组”列表中。 Though MySQL won't give you an error even if you don't.
尽管MySQL不会给您一个错误,即使您没有。
For this matter, you either add Top20 into group by, or remove Top20 from select: 为此,您可以将Top20添加到group by中,或者从选择中删除Top20:
SELECT pageType, Top20/count(DISTINCT requestId) as Percentage
FROM (
SELECT pageType, requestId,
SUM(CASE WHEN rank <= 20 THEN 1 ELSE 0 END) as Top20
FROM tempTable
GROUP BY pageType, requestId
) tempTable
GROUP BY pageType
http://sqlfiddle.com/#!9/e7eb89/4 http://sqlfiddle.com/#!9/e7eb89/4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.