MySQL - How to unpivot columns to rows?

前端 未结 3 2248
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 08:58

I\'m probably not seeing things very clear at this moment, but I have a table in MySQL which looks like this:

ID | a  | b  | c 
1  | a1 | b1 | c1
2  | a2 | b         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 09:29

    You are trying to unpivot the data. MySQL does not have an unpivot function, so you will have to use a UNION ALL query to convert the columns into rows:

    select id, 'a' col, a value
    from yourtable
    union all
    select id, 'b' col, b value
    from yourtable
    union all
    select id, 'c' col, c value
    from yourtable
    

    See SQL Fiddle with Demo.

    This can also be done using a CROSS JOIN:

    select t.id,
      c.col,
      case c.col
        when 'a' then a
        when 'b' then b
        when 'c' then c
      end as data
    from yourtable t
    cross join
    (
      select 'a' as col
      union all select 'b'
      union all select 'c'
    ) c
    

    See SQL Fiddle with Demo

提交回复
热议问题