sql >> Databasteknik >  >> RDS >> Mysql

MySQL - Hur kan man koppla bort kolumner till rader?

Du försöker avpivotera uppgifterna. MySQL har ingen unpivot-funktion, så du måste använda en UNION ALL fråga för att konvertera kolumnerna till rader:

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

Se SQL-fiol med demo .

Detta kan också göras med en 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

Se SQL-fiol med demo



  1. Får körningsbehörighet till xp_cmdshell

  2. Ändra ett SQL Server Agent Schema (T-SQL)

  3. ORA-00911:ogiltigt tecken

  4. Hur man listar alla databaser med PostgreSQL