sql select 5 higest values

181 views Asked by At

I'm trying to select the 5 rows with the highest count value

This is my query:

string sql = "SELECT   top 5  count FROM  Likes  ORDER BY COUNT(*) DESC";

It's just throwing an error code that

Column 'Likes.count' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

It's for a project I've got to present tomorrow... enter image description here

3

There are 3 answers

0
Dan On BEST ANSWER

On SQL Server, simply do this:

 SELECT TOP 5 * FROM Likes ORDER BY [Count] DESC

This assumes that your Likes-table already contains a column named [Count] meaning that you don't need to count the records yourself (which is what COUNT(*) does).

0
Raging Bull On

You should not use COUNT(*) here for order by.

SELECT   top 5  [count] FROM  Likes  ORDER BY [Count] DESC
0
Ash Burlaczenko On

count is a reserved word which is why you should stay clear of using them for column names. If you don't want to rename the column you can escape it, different dbms may effect who you do this. In ssms you would use square brackets.

string sql = "SELECT   top 5  [count] FROM  Likes  ORDER BY COUNT(*) DESC";