我有以下表格:
评分
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
使用MySQL,我想创建一个如下所示的表:
----- User1 User2 User3 ...
ISBN1 Rating11 NaN Nan
ISBN2 NaN Rating21 Rating23
ISBN3 Rating31 NaN NaN
...
我已经学会了如何为固定数量的列here执行此操作。但是如何将行转换为列?我尝试过像
这样的东西 create view BX-Book-Ratings-Extended as (
select
ISBN ,
case when
书本评分= "1" then 1 end as
用户ID ,
case when
书本评分= "2" then 2 end as
用户ID ,
case when
书本评分{ {1}}用户ID = "3" then 3 end as
书本评分,
case when
用户ID = "4" then 4 end as
书本评分,
case when
用户ID = "5" then 5 end as
BX-书本评分{ {1}}
哪个不起作用 - 视图为空...我也尝试采用another线程的解决方案,但一直遇到一个我无法识别的语法错误:
from
数据集为here。
感谢您的任何建议!
答案 0 :(得分:1)
您对动态SQL(准备/执行)的第二次尝试是关闭的 试试这个问题:
SET @sql = NULL;
SELECT Concat(
'SELECT ISBN, ',
Group_Concat( x SEPARATOR ','),
' FROM ratings GROUP BY ISBN '
)
INTO @sql
FROM (
SELECT Concat('Max( CASE WHEN User_ID = ',
User_ID,
' THEN Book_Rating END ) As User_',
User_ID
) As x
FROM ratings
GROUP BY User_ID
ORDER BY User_ID
) x;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
演示:http://rextester.com/GLJV4738
如果一个用户可以为一本图书获得更多评分,请将max
替换为sum
。
不幸的是,由于MySql limits
,此解决方案不应超过数千个用户(列)的副本