我有一个名为Grade的表:
+--------+--------+-----------+
| userid | itemid | finalgrade|
+--------+--------+-----------+
| 1 | 7 | 100 |
| 1 | 8 | 89 |
| 2 | 7 | 87 |
| 2 | 8 | 17 |
| 3 | 7 | 87 |
| 3 | 8 | 38 |
+--------+--------+-----------+
我想创建一个透视查询,将表格改为:
+--------+---+---+
| userid | 7 | 8 |
+--------+---+---+
| 1 |100| 89|
| 2 |87 | 17|
| 3 |87 | 38|
+--------+---+---+
我有一个解决方案,使用像这样的定义itemid:
select *,
truncate (sum(finalgrade*(1-abs(sign(itemid-7)))),0) as 7,
truncate (sum(finalgrade*(1-abs(sign(itemid-8)))),0) as 8,
FROM grades
group by userid"
问题是我需要相同的查询,但没有定义itemid,动态创建列。
答案 0 :(得分:1)
我认为您需要这样的查询:
SELECT userid,
MAX(CASE WHEN itemid=7 THEN finalgrade END) as c7,
MAX(CASE WHEN itemid=8 THEN finalgrade END) as c8,
FROM grades
GROUP BY userid
但是你希望它具有动态值,然后你可以使用这样的预备语句:
SELECT
CONCAT(
'SELECT userid,',
GROUP_CONCAT(CONCAT('MAX(CASE WHEN itemid=', itemid, ' THEN finalgrade END) AS c', itemid)),
' FROM tablename GROUP BY userid')
FROM (SELECT DISTINCT itemid FROM tablename) s INTO @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
您可以使用SUM而不是MAX,具体取决于数据的结构。