简体   繁体   中英

how do I get the top 3 columns items based on a given column

Given this sample table:

ID_no         name             grade
112           Micheal          81
113           Airi             90
114           Felix            76
115           Ana              87

how do i get the top 3 names based on their given grades...

You just have to use the TOP clause in combination with your desired order:

SELECT TOP 3 Name, SUM(Grade)AS Grade
FROM table
GROUP BY Name
ORDER BY Grade DESC

(assuming that a higher grade is better)

Note that you need SELECT TOP 3 WITH TIES (as John has shown) to include all rows with the same number. So consider that there are 5 names with the same grade, my query would only return 3 whereas WITH TIES ensures that all 5 are returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM