SQL 计数,按降序排列并选择前 5 名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13734769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:27:38  来源:igfitidea点击:

Count, order desc and select top 5

sqlsql-serversql-server-2012

提问by Ray Alex

SQL Server 2012

SQL Server 2012

We have a table, like such:

我们有一张桌子,像这样:

ticket, type
------------------
1234, hardware
1543, software
8859, network
5832, hardware
4900, hardware
8403, software
7859, network
4332, telephone
8721, database

Our goal is to count up all tickets belonging to each type (so in this case the result should be 3 hardware, 2 software, 2 network, 1 telephone and 1 database ticket(s)), order them desc and select the first 5 resulting rows.

我们的目标是计算属于每种类型的所有票证(因此在这种情况下,结果应该是 3 个硬件、2 个软件、2 个网络、1 个电话和 1 个数据库票证),将它们按 desc 排序并选择前 5 个结果行。

We're trying to determine the top 5 "popular" or most seen ticket types (and how many there are).

我们正在尝试确定前 5 名“流行”或最常看到的门票类型(以及有多少)。

I've got the counting portion down but not sure how to proceed with ordering desc and selecting the first 5.

我已经把计数部分记下来了,但不知道如何继续订购 desc 并选择前 5 个。

Thank you!

谢谢!

回答by Taryn

In SQL Server you can use TOPto select a certain number of rows along with an order by to get the proper records:

在 SQL Server 中,您可以使用TOP按顺序选择一定数量的行以获取正确的记录:

select top 5 type, count(*) Total
from yourtable
group by type
order by total desc

See SQL Fiddle with Demo

参见SQL Fiddle with Demo

回答by Majid Laissi

select * from (
    select type, count(*) 
    from table
    group by type
    order by 2 desc
)
where rownum <=5