How to sum the duplicate values from mysql table

2019-03-06 09:50发布

i wanted to retrieve the sum of duplicate USD amount from below table with respect to date and ref_nr columns

uid         date       USD      Ref_Nr
1     2018-04-11    1       7 
1     2018-04-11    2       7
1     2018-04-11    3       8
1     2018-04-11    4       8
1     2018-04-11    6       6
1     2018-04-11    6       6 
1     2018-04-10    3       7
1     2018-04-10    5       7
1     2018-04-10    2       8
1     2018-04-10    2       8

Here is my sql query and what i tried, but iam not getting proper output, please help me

SELECT  uid 
     ,  date 
     , SUM(USD) AS USD 
     ,  Ref_Nr  
  FROM my_table
 GROUP 
    BY `date`;

Here is expected output

uid         date       USD      Ref_Nr 
1     2018-04-11    3       7  
1     2018-04-11    7       8 
1     2018-04-11    12      6 
1     2018-04-10    8       7 
1     2018-04-10    4       8

1条回答
\"骚年 ilove
2楼-- · 2019-03-06 10:36
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.

查看更多
登录 后发表回答