我想找出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 %。那我该怎么处理呢?
发布于 2020-06-22 17:06:42
您尝试的查询至少有3个问题:
如果要按播放次数排序,请按username...排序;不要按username...排序
order by放在子查询子句之外:通过count(*) as n_plays给count(*)一个别名,然后对外部查询order by n_plays desc进行排序。select列表中声明的别名在order by子句中可用,因此不需要子查询(或CTE或其他什么)。percent,对吗?所以只需隔离top 30 *,而不是top 30 *所以,让我们把这一切放在一起:
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
发布于 2020-06-22 17:02:33
您需要将order移动到子查询之外,并且您应该按c命令来捕获前30%。
试试这个..。
select top 30 percent *
from
(select username, count(*) as c
from plays
group by username
) t
order by c desc在您的问题中,您提到了获得前30名的结果,如果是这样的话,请从查询中删除“%”。
发布于 2020-06-22 18:07:40
不要使用子查询:
select top 30 percent username, count(*) as c
from plays
group by username
order by count(*) deschttps://stackoverflow.com/questions/62519470
复制相似问题