I’m stumped by pivoting a table and the frustration level is rising. I realize the answer is probably in front of me but I can’t find it. I’ve tried case statements, group_concat, subqueries all to no avail.
How to get the current table…
super_id cat_id qa qb
1 1 5 5
1 2 2 5
1 3 3 4
2 4 5 3
2 5 3 4
2 6 4 2
to look like this…
1 2 <--- super_id
qa 3.33 4.00 <--- avg
qb 4.67 3.00
Thanks!
As already mentioned, MySQL isn’t built to pivot on its own and you should probably pivot in code if possible, but barring that, below is some example SQL that should do what you want. Assuming your actual table is variable in some sense (like how many q[x] columns you have, or how many super_id’s you have), you can wrap this up in a stored procedure to dynamically generate and execute the necessary SQL.
Assuming an initial table named testTable:
Use the following SQL:
To achieve this result:
(edit: formatting)