I am a very beginner to mysql and sql in general. None of my search results brought the solution I am looking for. I have a database and need to format the output like in the example below. Unfortunately I can't change the database anymore since it's an old project of another employee.
The source table:
CustomerID serviceID ratingID employeeID
1 1 A 1
1 2 B 5
1 3 B 2
1 4 A 3
2 1 A 1
2 2 C 5
2 3 D 2
2 4 C 3
3 1 T 1
3 2 O 5
3 3 T 2
3 4 O 3
Each Customer has four entries, one for each service. They have set ratings and employees.
The output that I need (employeeID can be ignored):
CustomerID ServiceID=1 ServiceID=2 ServiceID=3 ServiceID=4
1 A B B A
2 A C D C
3 T O T O
I found solutions with group_concat(if())... in the select statement and grouping by customerID, which only brought the values of "1" in each field and not the related values. I tried tying lose selects together with union or subselects but none gave the result I am looking for. Does anybody have a beginner friendly help?
For this sample data you can use conditional aggregation:
select CustomerID,
max(case when serviceID = 1 then ratingID end) `ServiceID=1`,
max(case when serviceID = 2 then ratingID end) `ServiceID=2`,
max(case when serviceID = 3 then ratingID end) `ServiceID=3`,
max(case when serviceID = 4 then ratingID end) `ServiceID=4`
from tablename
group by CustomerID
See the demo.
Results:
| CustomerID | ServiceID=1 | ServiceID=2 | ServiceID=3 | ServiceID=4 |
| ---------- | ----------- | ----------- | ----------- | ----------- |
| 1 | A | B | B | A |
| 2 | A | C | D | C |
| 3 | T | O | T | O |