"employee" Table
| emp_id | empName |
|---|---|
| 1 | ABC |
| 2 | xyx |
"client" Table:
| id | emp_id | clientName |
|---|---|---|
| 1 | 1 | a |
| 2 | 1 | b |
| 3 | 1 | c |
| 4 | 2 | d |
"collection" Table
| id | emp_id | Amount |
|---|---|---|
| 1 | 2 | 1000 |
| 2 | 1 | 2000 |
| 3 | 1 | 1000 |
| 4 | 1 | 1200 |
I want to aggregate values from the three tables input tables here reported as samples. For each employee I need to find
- the total collection amount for that employee (as a sum)
- the clients that are involved with the corresponding employee (as a comma-separated value)
Here follows my current query.
MyQuery:
SELECT emp_id,
empName,
GROUP_CONCAT(client.clientName ORDER BY client.id SEPARATOR '') AS clientName,
SUM(collection.Amount)
FROM employee
LEFT JOIN client
ON clent.emp_id = employee.emp_id
LEFT JOIN collection
ON collection.emp_id = employee.emp_id
GROUP BY employee.emp_id;
The problem of this query is that I'm getting wrong values of sums and clients when an employee is associated to multiple of them.
Current Output:
| emp_id | empName | clientName | TotalCollection |
|---|---|---|---|
| 1 | ABC | a,b,c,c,b,a,a,b,c | 8400 |
| 2 | xyz | d,d | 1000 |
Expected Output:
| emp_id | empName | clientName | TotalCollection |
|---|---|---|---|
| 1 | ABC | a , b , c | 4200 |
| 2 | xyz | d | 1000 |
How can I solve this problem?