Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL Server
Expertise: Beginner
Mar 21, 2000

Select Maximum Five Result

Question:
How do I find out the top-five best sale items? I want the maximum five items to be listed.

Answer:
In version 7, SQL Server has conveniently provided the TOP keyword. So, using the pubs database for an example, the following query will return the books with the top three sales:

use pubs
go
select top 3 title_id,sum(qty)
from sales
group by title_id
order by sum(qty) desc
Please note that the keyword TOP does not mean "highest" or "maximum"; it simply means the first n rows of the result set. That is why, in order to get the three books with the highest sales, I had to sort the result set in descending order. Had I allowed the default sort order of ascending, I would have received the three books with the lowest sales.

Another option with the TOP keyword is to use TOP N PERCENT. This limits the result set to the first n percentage of rows.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date