Home  >  Q&A  >  body text

MySQL - How to convert columns to rows?

<p><br /></p> <pre class="brush:php;toolbar:false;">ID | a | b | c 1 | a1 | b1 | c1 2 | a2 | b2 | c2</pre> <p>How to reorganize rows into IDs, column headers, values? </p> <pre class="brush:php;toolbar:false;">1 | a1 | a 1 | b1 | b 1|c1|c 2 | a2 | a 2 | b2 | b 2 | c2 | c</pre> <p><br /></p>
P粉533898694P粉533898694453 days ago531

reply all(1)I'll reply

  • P粉511896716

    P粉5118967162023-07-25 00:05:48

    You are trying to reverse the data. MySQL does not have a reverse function, so you need to use a UNION ALL query to convert columns to 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 achieved using 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

    reply
    0
  • Cancelreply