如何在SQLite中转置表格?

时间:2018-10-24 04:45:57

标签: sql sqlite transpose

您好,所以我在SQlite中有一个表格:

   User    |  Group  |   Role    
John Smith |   A     |   admin
John Smith |   B     |   user
Jane Doe   |   A     |   user
Jane Doe   |   B     |   limit
Jane Doe   |   C     |   admin
Jack Brown |   A     |   admin, user

我想转置表格,所以每行只有一个用户。列标题为“组” 。 “组”的值应为第一张表的“角色” 列中的值。

因此,转换后的外观如下:

   User    |    A        |    B       |  C 
John Smith |   admin     |    user    |
Jane Doe   |   user      |    limit   | admin
Jack Brown |   admin,user|            |

人们将如何做这个SQLite?

3 个答案:

答案 0 :(得分:1)

您可以使用row_number()并进行聚合:

select User, 
       max(case when seq = 1 then role end) as a,
       max(case when seq = 2 then role end) as b,
       max(case when seq = 3 then role end) as c
from (select t.*,
             row_number() over (partition by User order by group) as seq
      from table t
     ) t
group by User;

答案 1 :(得分:1)

无需使用窗口函数,因为"Group"列已经提供了转换所需的值。这不仅简化了查询,而且还将这些值放在正确的转换列中,而与顺序无关,也不管“组”值是否连续。 (还要注意,sqlite会抱怨如果使用group而不使用分隔符,因为它是保留关键字。)

SELECT User, 
       max(CASE WHEN "group" == 'A' THEN role END) as A,
       max(CASE WHEN "group" == 'B' THEN role END) as B,
       max(CASE WHEN "group" == 'C' THEN role END) as C
FROM SO52961250 t
GROUP BY User;

答案 2 :(得分:0)

@CPerkins提供的出色解决方案可能会丢失信息。例如,考虑如果“杰克·布朗”的数据显示在两行中,将会发生什么情况:

Jack Brown |   A     |   admin
Jack Brown |   A     |   user

为确保不会丢失任何信息,可以使用GROUP_CONCAT而不是MAX:

SELECT User, 
       GROUP_CONCAT(CASE WHEN "group" == 'A' THEN role END) as A,
       GROUP_CONCAT(CASE WHEN "group" == 'B' THEN role END) as B,
       GROUP_CONCAT(CASE WHEN "group" == 'C' THEN role END) as C
FROM SO52961250 t
GROUP BY User;