SQL query with distinct and sum

此生再无相见时 提交于 2019-11-27 23:36:00
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).

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.

SELECT `color`,`fruit`,SUM(`rating`)
FROM Medleys
GROUP BY `color`,`fruit`

SQL Fiddle Example

ljh

This should answer your question:


SELECT color, fruit, sum(rating) as [sum]
FROM medleys
GROUP BY color, fruit
ORDER BY color
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!