I have the following tables:
RATINGS
User-ID ISBN Book-Rating
244662 0373630689 3
19378 0812515595 2
238625 0441892604 5
180315 0140439072 1
242471 3548248950 1
BOOKS
ISBN Book-Title Book-Author Year-Of-Publication Publisher
0393000753 A Reckoning May Sarton 1981 W W Norton
Using MySQL, I want to create a table that looks like this:
----- User1 User2 User3 ...
ISBN1 Rating11 NaN Nan
ISBN2 NaN Rating21 Rating23
ISBN3 Rating31 NaN NaN
...
I've learned how to do it for a fixed number of columns here. But how to convert the rows into columns? I have tried something like
create view BX-Book-Ratings-Extended as (
select
ISBN,
case when
Book-Rating= "1" then 1 end as
User-ID,
case when
Book-Rating= "2" then 2 end as
User-ID,
case when
Book-Rating= "3" then 3 end as
User-ID,
case when
Book-Rating= "4" then 4 end as
User-ID,
case when
Book-Rating= "5" then 5 end as
User-ID
from
BX-Book-Ratings
)
which doesn't work - the view is empty... I also tried to adopt a solution from another thread, but keep getting a syntax error I can't identify:
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'ifnull(SUM(case when `Book-Rating` = ''',
`User-ID`,
''' then `Book-Rating` end),0) AS ',
`User-ID`
)
) INTO @sql
FROM
`BX-Book-Ratings`;
SET @sql = CONCAT('SELECT ISBN, ', @sql, '
FROM BX-Book-Ratings
GROUP BY ISBN');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
The dataset is here.
Thanks for any advice!