Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL count row values WHERE column = value

I have a database that looks pretty much like this:

enter image description here

I wanna make a MySQL query where I count the votes for each id and order them by starting from the highest. I want the output to be like:

enter image description here

Is it possible without making like 3 queries inside each other?

like image 266
Cheezen Avatar asked May 19 '13 22:05

Cheezen


People also ask

How count rows with specific value in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

Can count be used in WHERE clause?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause.

How do I count rows in MySQL?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.


1 Answers

select
    name,
    sum(votes) as total_votes
from mytable
group by 1
order by 2 desc
like image 130
Bohemian Avatar answered Oct 09 '22 20:10

Bohemian