Meredith
Meredith

Reputation: 840

Specific SQL sorting

I have a database with 4 relevant columns.

Let's say it looks like this:

+--------+-------+-------+-------+
|USERNAME|POINTS1|POINTS2|POINTS3|
+--------+-------+-------+-------+
|Meredith|10     |15     |18     |
+--------+-------+-------+-------+
|User2   |13     |12     |11     |
+--------+-------+-------+-------+
|User3   |10     |3      |4      |
+--------+-------+-------+-------+
|Meredith|4      |9      |17     |
+--------+-------+-------+-------+

I'd like to sort by the total number of points, so that I'd get a result like this:

+--------+-----+
|USERNAME|TOTAL|
+--------+-----+
|Meredith|73   |
+--------+-----+
|User2   |36   |
+--------+-----+
|User3   |17   |
+--------+-----+

Right now, I'm using SELECT username, (points1 + points2 + points3) FROM table_name ORDER BY (points1 + points2 + points3) DESC LIMIT 0, 10, which gives a result like this:

+--------+-----+
|USERNAME|TOTAL|
+--------+-----+
|Meredith|43   |
+--------+-----+
|User2   |36   |
+--------+-----+
|Meredith|30   |
+--------+-----+
|User3   |17   |
+--------+-----+

I'm not sure how to combine multiple results. It is not an option to combine both rows into a single row.

Upvotes: 0

Views: 50

Answers (1)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Something like this:

SELECT username, sum(points1 + points2 + points3) points 
FROM table_name
GROUP BY username
ORDER BY points DESC
LIMIT 0, 10

Upvotes: 4

Related Questions