SQL query with distinct and sum

前端 未结 4 780
天涯浪人
天涯浪人 2020-12-06 04:46

I have the following medleys table that combines colors, fruits and ratings:

[medleys]
medley_id   |   co         


        
相关标签:
4条回答
  • 2020-12-06 05:33
    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).

    0 讨论(0)
  • 2020-12-06 05:41
    SELECT `color`,`fruit`,SUM(`rating`)
    FROM Medleys
    GROUP BY `color`,`fruit`
    

    SQL Fiddle Example

    0 讨论(0)
  • 2020-12-06 05:44

    This should answer your question:

    
    SELECT color, fruit, sum(rating) as [sum]
    FROM medleys
    GROUP BY color, fruit
    ORDER BY color
    

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题