[英]MySQL pivoting with VARCHAR
Let say I have the table 'Organization' with two columns 'Name' and 'Role'. 假设我的表'Organization'有两列'Name'和'Role'。 The field 'Name' contains a string, similarly 'Role' can be a string in the following list: ['Admin', 'Moderator', 'User']. 字段'Name'包含一个字符串,类似'Role'可以是以下列表中的字符串:['Admin','Moderator','User']。
I would like to perform a query that prints me the users sorted by roles. 我想执行一个查询,打印我按角色排序的用户。 For instance, having the following starting table: 例如,有以下起始表:
+++++++++++++++++++++++
+ Name + Role +
+++++++++++++++++++++++
+ Sara + User +
+ Tony + Admin +
+ John + User +
+++++++++++++++++++++++
I would like to obtain the following query: 我想获得以下查询:
++++++++++++++++++++++++++++++++++++++++
+ Admin + Moderator + User +
++++++++++++++++++++++++++++++++++++++++
+ Tony + NULL + Sara +
+ NULL + NULL + John +
++++++++++++++++++++++++++++++++++++++++
The best solution I came up so far is the following, but I would like to have a more compact solution. 到目前为止我提出的最佳解决方案如下,但我希望有一个更紧凑的解决方案。 What I need is to separate the columns and then rejoin them, but I do not know how to do this... 我需要的是分离列然后重新加入它们,但我不知道如何做到这一点......
SELECT CASE WHEN Role = 'Admin' THEN Name END AS 'Admin',
CASE WHEN Role = 'Moderator' THEN Name END AS 'Moderator',
CASE WHEN Role= 'User' THEN Name END AS 'User'
FROM Organization;
++++++++++++++++++++++++++++++++++++++++
+ Admin + Moderator + User +
++++++++++++++++++++++++++++++++++++++++
+ NULL + NULL + Sara +
+ Tony + NULL + NULL +
+ NULL + NULL + John +
++++++++++++++++++++++++++++++++++++++++
To do this you can use equivalent of ROW_NUMBER
and GROUP BY
calculated RowNumber column: 为此,您可以使用等效的ROW_NUMBER
和GROUP BY
计算的RowNumber列:
SELECT
MAX(CASE WHEN Role = 'Admin' THEN Name END) AS `Admin`,
MAX(CASE WHEN Role = 'Moderator' THEN Name END) AS `Moderator`,
MAX(CASE WHEN Role = 'User' THEN Name END) AS `User`
FROM (
SELECT *
,@row_num := IF(@prev_value=concat_ws('',t.Role),@row_num+1,1) AS RowNumber
,@prev_value := concat_ws('',t.Role)
FROM Organization t,
(SELECT @row_num := 1) x,
(SELECT @prev_value := '') y
ORDER BY t.Role
) AS sub
GROUP BY RowNumber
Output: 输出:
╔═════════╦════════════╦══════╗
║ Admin ║ Moderator ║ User ║
╠═════════╬════════════╬══════╣
║ Tony ║ (null) ║ Sara ║
║ (null) ║ (null) ║ John ║
╚═════════╩════════════╩══════╝
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.