I have the following medleys
table that combines colors
, fruits
and ratings
:
[medleys]
medley_id | co
SELECT color, fruit, sum(rating)
FROM medleys
GROUP BY color, fruit
Distinct is used to select distinct elements, nothing more, while you want to aggregate and for that you need GROUP BY
and aggregation functions (SUM
).
SELECT `color`,`fruit`,SUM(`rating`)
FROM Medleys
GROUP BY `color`,`fruit`
SQL Fiddle Example
This should answer your question:
SELECT color, fruit, sum(rating) as [sum]
FROM medleys
GROUP BY color, fruit
ORDER BY color
You don't need distinct
at all. You need group by
:
select color, fruit, sum(rating)
from medleys
group by color, fruit
I'm answering, because I see this mistake occur. In general, you don't need select distinct
at all in SQL. You can always use a group by
instead. Distinct
should be introduced after group by
as a convenient short-hand.