【问题标题】:Select distinct values as distinct columns in the same row选择不同的值作为同一行中的不同列
【发布时间】:2014-09-08 15:07:07
【问题描述】:

正如标题所说,我想选择不同的值作为同一行中的不同列

例子:

ID    CATEGORY
1     5
1     6
1     8
2     5
2     7
3     5

我想要这样的东西:

ID     CATEGORY1    CATEGORY2    CATEGORY3
1      5            6            8
2      5            7            
3      5

只能在一个查询中使用吗?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    获得这样的东西的最简单方法是使用group_concat()

    select id, group_concat(category order by category)
    from table t
    group by id;
    

    但是,它会创建一个包含值列表的附加列,而不是三列。这足以满足您的目的吗?

    如果您想要三个额外的列,那么您将需要一个更复杂的语句。这是使用变量的一种方法:

    select id,
           max(case when seqnum = 1 then category end) as category1,
           max(case when seqnum = 2 then category end) as category2,
           max(case when seqnum = 3 then category end) as category3
    from (select t.*,
                 (@rn := if(@id = id, @rn + 1,
                            if(@id := id, 1, 1)
                           )
                 ) as seqnum
          from table t cross join
               (select @rn := 0, @id := NULL) vars
          order by id, category
         ) t
    group by id;
    

    【讨论】:

    • [group_concat(category ORDER BY category)]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2012-11-08
    • 2017-01-26
    • 2018-12-09
    • 2013-02-11
    相关资源
    最近更新 更多