Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count, order desc and select top 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

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.

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

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

Thank you!

like image 557
Ray Alex Avatar asked Dec 05 '12 23:12

Ray Alex


2 Answers

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

See SQL Fiddle with Demo

like image 90
Taryn Avatar answered Sep 20 '22 02:09

Taryn


select * from (
    select type, count(*) 
    from table
    group by type
    order by 2 desc
)
where rownum <=5
like image 32
Majid Laissi Avatar answered Sep 21 '22 02:09

Majid Laissi