计数,按降序排列并选择前 5 名 [英] Count, order desc and select top 5

查看:37
本文介绍了计数,按降序排列并选择前 5 名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

我们正在尝试确定前 5 种流行"或最常出现的门票类型(以及有多少种).

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

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

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

谢谢!

推荐答案

在 SQL Server 中,您可以使用 TOP 来选择一定数量的行以及一个 order by 以获得正确的记录:

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

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

参见SQL Fiddle with Demo

这篇关于计数,按降序排列并选择前 5 名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆