如何正确使用rank-over

t3irkdon  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(306)

错误:您的sql语法有错误;请查看与您的mysql服务器版本对应的手册,以了解使用near'(partition by name order by counts desc)作为rank from(select name,count(case\)在第4行的正确语法

select Name, counts
from (
select Name, counts,
rank()over(partition by name order by counts desc) as rank
from (
select Name, count(Case_Id) as counts,
from CTD a
left join Agent_Table b 
on a.Agent_ID = b.Agent_ID
group by Name )
group by Name )
where rank < = 2;

请参阅下面的创建表
如果不存在,则创建表 Agent_Table ( Agent_ID 整数(5), Name varchar(20));
插入 Agent_Table ( Agent_ID , Name )值('1','vijay'),('2','rajesh'),('3','satish'),('4','anji');
如果不存在,则创建表 CTD ( Case_Id 整数(5), Stage 瓦尔查尔(20), Login_Time 瓦尔查尔(50), Logout_Time 瓦尔查尔(50), Agent_ID 整数(5), Status varchar(20));
插入 CTD ( Case_Id , Stage , Login_Time , Logout_Time , Agent_ID , Status )值('101','maker','5/11/2019 10:20','10:30','2','success'),('102','maker','5/11/2019 10:25','10:35','1','success'),('103','maker','5/11/2019 10:40','10:50','2','success'),('101','checker','5/11/2019 10:45','11:00','3','success'),('101','approver','5/11/2019 11:15','11:30','2','success'),('102','checker','5/11/2019 10:50'、'11:00'、'1'、'reject')、('102'、'maker'、'5/11/2019 11:15'、'11:45'、'4'、'reverify')、('103'、'checker'、'5/11/2019 11:30'、'11:40'、'2'、'reject')

ql3eal8s

ql3eal8s1#

您尚未提供 alias 对于子查询,这可能是您得到错误的原因。
请尝试以下操作

select 
    Name, 
    counts
from 
(
    select 
        Name, 
        counts,
        rank() over(partition by Name order by counts desc) as rn
    from 
    (
        select 
            Name, 
            count(Case_Id) as counts
        from CTD a
        left join Agent_Table b 
        on a.Agent_ID = b.Agent_ID
        group by 
            Name
    ) subq
) sub
where rn <= 2;
jljoyd4f

jljoyd4f2#

你有一个不必要的逗号,缺少必要的别名。在任何情况下,窗口函数都是在 group by 因此,您可以将查询简化为

select Name, 
       counts
from (select Name, 
             count(Case_Id) as counts,
             rank() over (partition by name order by count(Case_Id) desc) as rnk
       from CTD a
       left join Agent_Table b on a.Agent_ID = b.Agent_ID
       group by Name) t1
where rank < = 2;

相关问题