How to sum the duplicate values from mysql table

Deadly 提交于 2019-12-02 10:06:37
SELECT  uid 
     ,  date 
     , SUM(USD) AS USD 
     ,  Ref_Nr  
  FROM my_table
 GROUP 
    BY `date`, Ref_Nr, uid;

In this case you must have Ref_Nr in the group by to get the desired results. uid, based on sample data, isn't needed; but it is wise to always group by the non-aggregated fields from the select in the group by. The only reason this works in mySQL is because they extend the group by; most other RDBMS would throw an error about the missing non-aggregated fields in the group by. In version 5.7.5 and higher this feature is disabled by default where enabled by default prior.

As to why ref_nr is needed in the group by:

The mySQL engine believes you want to just group by date. So all the ref_NR's get summed together and the system simply picks one per date to display; same for uid; but since they are all the same; you don't care. This in'st the case with the ref_nr.

So to resolve the issue, just add ref_nr to the group by and out of good from add UID. So it is good from to group by all non-aggregated columns from the select into the group by.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!