Yuval Karmi
Yuval Karmi

Reputation: 26713

SQL - How to use SUM and MAX in same query?

I am working with a MySQL database version 5.0.41 (and PHP 5.2.6, though that may not be relevant to this question).

I have a table called votes with the following fields: id, item_id, vote_value. Each time a user on the site submits a positive vote for an item, a new row is created with the corresponding item_id and a positive number (i.e. 1). When the vote is negative, a row is created with the corresponding item_id and a negative number (i.e. -1). I'd like to select, with one query (if possible), the item_id that has the most votes. To do this, I first need to sum up all the votes for each individual item_id (to get a number like 38 or -14) and then select the maximum for that number. I am not sure how to write the query for that.

Could you help?

Thanks!

Upvotes: 0

Views: 3726

Answers (2)

VoteyDisciple
VoteyDisciple

Reputation: 37813

You could do something like:

SELECT item_id, SUM(vote_value) AS total, COUNT(id) AS c
FROM votes
GROUP BY item_id
ORDER BY total DESC, c DESC
LIMIT 1

Upvotes: 1

Zed
Zed

Reputation: 57668

SELECT item_id, SUM(vote_value) AS sum
FROM votes
GROUP BY item_id
ORDER BY sum DESC
LIMIT 1

Upvotes: 3

Related Questions