子查询中不允许sql order by

kq0g1dla  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(352)

我正在努力让前30名球员谁玩了游戏最多。但是,我似乎无法从排序的子查询中检索。

select top 30 percent * 
from 
    (select username, count(*) as c 
     from plays 
     group by username
     order by username desc) t

如果没有命令 top 30 percent 将只反映输出的前30%。那我怎么把它分类呢?

8qgya5xd

8qgya5xd1#

您尝试的查询至少有3个问题:
如果你想按播放次数降序排列,那么就这样做;不按排序 username ...
简单地说 order by 在subquery子句之外:give count(*) 别名via count(*) as n_plays 然后对外部查询进行排序 order by n_plays desc . 中声明的别名 select 列表可在 order by 子句,因此不需要子查询(或cte或其他任何东西)。
如果你想要前30名球员,那就不是前30名了 percent ,是吗?所以只要隔离 top 30 * ,否 percent .
所以,让我们把它们放在一起:

select top 30
  username,
  count(*) as n_plays
from plays
group by username
order by n_plays desc;

数据创建者:

create table plays (
  id int identity not null primary key,
  username varchar(100)
  -- other fields like date/time, comment, etc.
);

declare @i int = 1;

while @i <= 1000
begin
  insert into plays (username)
  values ( 'Player' + cast( cast(rand() * 99 as int) as varchar) );

  set @i += 1;
end;

工作小提琴:http://sqlfiddle.com/#!18/aebdf/4号

ruarlubt

ruarlubt2#

您需要将order by移到子查询之外,并且您应该按c排序以捕获前30%。
试试这个。。

select top 30 percent * 
from 
    (select username, count(*) as c 
     from plays 
     group by username
     ) t
order by c desc

在您的问题中,您提到了获得前30个结果,如果是这种情况,请从查询中删除“百分比”。

xwmevbvl

xwmevbvl3#

不使用子查询:

select top 30 percent username, count(*) as c 
from plays 
group by username
order by count(*) desc
bogh5gae

bogh5gae4#

前30名你能做到吗?

select username, count(*) as c 
     from plays 
     group by username
     order by c desc
     LIMIT 30

相关问题