[英]Pivoting for rows as columns - rating database
我有以下表格:
评分
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 WW Norton
使用MySQL,我想创建一个如下表:
----- User1 User2 User3 ... ISBN1 Rating11 NaN Nan ISBN2 NaN Rating21 Rating23 ISBN3 Rating31 NaN NaN ...
我已经了解了如何在固定数量的列上执行此操作 。 但是如何将行转换为列呢? 我已经尝试过类似的东西
create view BX-Book-Ratings-Extended as ( select
ISBN , case when
Book-Rating = "1" then 1 end as
User-ID = "1" then 1 end as
, case when
Book-Rating = "2" then 2 end as
User-ID的, case when
= "2" then 2 end as
, case when
Book-Rating = "3" then 3 end as
User-ID = "3" then 3 end as
, case when
Book-Rating = "4" then 4 end as
User-ID = "4" then 4 end as
, case when
Book-Rating = "5" then 5 end as
End-ID from
BX -书评)
这不起作用-视图为空...我也试图从另一个线程采用解决方案,但不断收到语法错误,我无法识别:
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;
数据集在这里 。
感谢您的任何建议!
您第二次使用动态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的限制,该解决方案不应该为超过数千名用户(列)工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.