MySQL使用VARCHAR

时间:2015-12-12 16:43:31

标签: mysql sql

假设我有桌子'组织'有两列'姓名'和'角色'字段'名称'包含一个字符串,类似的'角色'可以是以下列表中的字符串:['管理员','主持人','用户']。

我想执行一个查询,向我打印按角色排序的用户。 例如,有以下起始表:

+++++++++++++++++++++++
+   Name   +   Role   +
+++++++++++++++++++++++
+   Sara   +   User   +
+   Tony   +   Admin  +
+   John   +   User   +
+++++++++++++++++++++++

我想获得以下查询:

++++++++++++++++++++++++++++++++++++++++
+   Admin   +   Moderator   +   User   +
++++++++++++++++++++++++++++++++++++++++
+   Tony    +      NULL     +   Sara   +
+   NULL    +      NULL     +   John   +
++++++++++++++++++++++++++++++++++++++++

我到目前为止提出的最佳解决方案如下,但我希望有一个更紧凑的解决方案。我需要的是分离列然后重新加入它们,但我不知道如何做到这一点......

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   +
++++++++++++++++++++++++++++++++++++++++

1 个答案:

答案 0 :(得分:3)

要执行此操作,您可以使用等效的ROW_NUMBERGROUP 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

SqlFiddleDemo

输出:

╔═════════╦════════════╦══════╗
║ Admin   ║ Moderator  ║ User ║
╠═════════╬════════════╬══════╣
║ Tony    ║ (null)     ║ Sara ║
║ (null)  ║ (null)     ║ John ║
╚═════════╩════════════╩══════╝