SUM(DISTINCT) Based on Other Columns

前端 未结 6 1338
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 11:23

I currently have a table that looks something like this:

+------+-------+------------+------------+
| id   | rate  | first_name | last_name  |
+------+-----         


        
6条回答
  •  旧时难觅i
    2020-12-10 12:09

    David said he found his answer as such:

    SELECT SUM(rate) FROM (SELECT * FROM records GROUP BY last_name, first_name) T1
    

    But when you do the GROUP BY in the inner query, I think you have to use aggregate functions in your SELECT. So, I think the answer is more like:

    SELECT SUM(rate) FROM (SELECT MAX(rate) AS rate FROM records GROUP BY last_name, first_name) T1
    

    I picked MAX() to pick only one "rate" for a "last_name, first_name" combination but MIN() should work the same, assuming that the "last_name, first_name" always leads us to the same "rate" even when it happens multiple times in the table. This seems to be David's original assumption - that for a unique name we want to grab the rate only once because we know it will be the same.

提交回复
热议问题