i have a details table with columns:
- user_id int
- code int
- value int
And i want to build a summary table that looks like:
- user_id int
- valueA int
- valueB int
In the details table, valueA would correspond to say, code 5, and valueB would correspond to say, code 6, so i'm looking for something like:
insert into summary (user_id,valueA,valueB) VALUES ( SELECT ??? from details );
The problem of course is that i'm looking at multiple rows from the "details" table to populate one row in the "summary" table.
Eg, if i had the following rows in details:
1 5 100
1 6 200
2 5 1000
2 6 2000
I want to end up with the following in the summary table:
1 100 200
2 1000 2000
Any ideas?
If you have a manageable set of codes (say just 5 and 6) you could do something like this:
You may need to modify your
JOIN
s depending on if your codes are not required as 1 to 1 relationship (i.e.LEFT JOIN
s).If you have a large set of codes, I would look into a cursor runs a similar query above over a result set of your codes or using a different technology, (i.e. PHP script).
MySQL doesn't have PIVOT/UNPIVOT syntax, which leaves you to use a combination of GROUP BY and CASE expressions:
beware: you will end up with multiple summary columns if user_id+code is not unique.
EDIT: