row_number()函数在MySQL中的聚合值

时间:2017-06-09 08:27:04

标签: mysql sql

row_number()中对汇总值实施MySQL功能,如下所示:

select 
section,
(SELECT COUNT(*)+1 
        FROM rpt_top_uv_hosts_d
        WHERE rpt_date>='2017-06-07' and rpt_date<='2017-06-08' and section is not null and section = a.section
        AND sum(uv) > a.uv
        group by section,room_id,domain,name ) as 'Rank',
sum(uv) as 'uv',
room_id,
domain,
name
from rpt_top_uv_hosts_d a
where rpt_date>='2017-06-07' and rpt_date<='2017-06-08' and section is not null
group by section,room_id,domain,name
order by section,Rank asc;

主要目的是在选定日期内将room_id按其对应的uv排名。但是,MySQL只返回一个句子:“Invalid use of group function”。

这个问题的原因是什么?子查询中不允许group by?以及如何解决这个问题?顺便说一句,此BI系统中不允许使用SQL变量。

感谢您的帮助..

我通过多子查询解决了这个问题,但SQL看起来很糟糕。希望这可以优化。

select 
    section,
    (select count(*)+1 from (select section,sum(uv) as uv_aggre,room_id,domain,name
    from rpt_top_uv_hosts_d
    WHERE rpt_date>='2017-06-07' and rpt_date<='2017-06-08' and section is not null
    group by section,room_id,domain,name) a 
    where a.section = demo.section AND a.uv_aggre > demo.uv_aggre) as rank,
    uv_aggre,
    name,
    room_id,
    domain
from
(select section,sum(uv) as uv_aggre,room_id,domain,name
from rpt_top_uv_hosts_d
WHERE rpt_date>='2017-06-07' and rpt_date<='2017-06-08' and section is not null
group by section,room_id,domain,name) as demo
order by section,rank;

1 个答案:

答案 0 :(得分:1)

在某些mysql版本中,group by必须包含select语句中的所有字段。所以你必须按照排名以及查询的方式进行分组。 你能不能尝试在最后一组中重新排名,看看会发生什么?对不起,我不能只评论你的帖子,因为我太新了。 #sqlmode_only_full_group_by

另外,使用HAVING重写这个,我没有看到你在哪里使用聚合函数,让我知道:)

    SELECT COUNT(*)+1 
    FROM rpt_top_uv_hosts_d
    WHERE rpt_date>='2017-06-07' and rpt_date<='2017-06-08' and section is 
    not null and section = a.section

    group by section,room_id,domain,name 
    HAVING  sum(uv) > a.uv