'More than 1 records with same id giving double data after join with another table
I am executing below query on two tables auditqueue_entry and rep_permission. Table rep_permission having multiple records against rep_id which results in giving double payment amount after using aggregating function sum.
Select aqe.rep_id, sum(aqe.payment) as aqauditcents
From cclog.auditqueue_entry as aqe
Left Join ccconf.rep_permission
On aqe.rep_id = rep_permission.rep_id
Where aqe.processedtime
Between "2015-11-09 00:00:00"
And "2015-11-10 00:00:00"
And processedtime > 0
And rep_permission.permission_id IN ($ids)
Group By aqe.rep_id
For ex:-
rep_permission table:
+--------+---------------+
| rep_id | permission_id |
+--------+---------------+
| 60421 | 21 |
| 60421 | 451 |
+--------+---------------+
auditqueue_entry table:
+--------+---------+
| rep_id | payment |
+--------+---------+
| 60421 | 120 |
+--------+---------+
Current Output:
+--------+--------------+
| rep_id | aqauditcents |
+--------+--------------+
| 60421 | 240 |
+--------+--------------+
Expected Output:
+--------+--------------+
| rep_id | aqauditcents |
+--------+--------------+
| 60421 | 120 |
+--------+--------------+
Solution 1:[1]
Find the required rep_ids in subquery and then join it
select aqe.rep_id, sum(aqe.payment) as aqauditcents
from cclog.auditqueue_entry as aqe
left join (
select distinct rep_id from rep_permission
where rep_permission.permission_id IN ($ids)
) rep_permission on aqe.rep_id = rep_permission.rep_id
where aqe.processedtime between "2015-11-09 00:00:00" and "2015-11-10 00:00:00"
and processedtime > 0
group by aqe.rep_id
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gurwinder Singh |
