這種類型的數據轉換稱爲UNPIVOT
。不幸的是,MySQL不具有unpivot功能,但您可以通過幾種不同的方式複製功能。
您可以使用UNION ALL
查詢到每個列的值轉換成行:
select member, dos, dx, seq
from
(
select member, dos, dx1 as dx, 'Dx1' as seq
from yourtable
union all
select member, dos, dx2 as dx, 'Dx2' as seq
from yourtable
union all
select member, dos, dx3 as dx, 'Dx3' as seq
from yourtable
union all
select member, dos, dx4 as dx, 'Dx4' as seq
from yourtable
union all
select member, dos, dx5 as dx, 'Dx5' as seq
from yourtable
) d
where dx is not null
order by member, seq;
見SQL Fiddle with Demo。這種方法會得到結果,但在大型表上可能效率不高。
另一種方法是使用交叉上的虛擬表JOIN:
select member, dos, dx, seq
from
(
select t.member, t.dos,
case s.seq
when 'Dx1' then dx1
when 'Dx2' then dx2
when 'Dx3' then dx3
when 'Dx4' then dx4
when 'Dx5' then dx5
end DX,
s.seq
from yourtable t
cross join
(
select 'Dx1' as seq union all
select 'Dx2' as seq union all
select 'Dx3' as seq union all
select 'Dx4' as seq union all
select 'Dx5' as seq
) s
) d
where dx is not null
order by member, seq;
參見SQL Fiddle with Demo。兩者都給出了結果:
| MEMBER | DOS | DX | SEQ |
|--------|---------------------------------|-------|-----|
| 12345 | January, 01 2011 00:00:00+0000 | 12142 | Dx1 |
| 12345 | January, 01 2011 00:00:00+0000 | 12345 | Dx2 |
| 12345 | January, 01 2011 00:00:00+0000 | 65657 | Dx3 |
| 12345 | January, 01 2011 00:00:00+0000 | 5657 | Dx4 |
| 12345 | January, 01 2011 00:00:00+0000 | 568 | Dx5 |
這並沒有表現得很好。我的數據很流行,其中Dx1,Dx2等是列 - 我需要它們是行,Seq告訴我它是哪個Dx#。謝謝。 – user3127999
@TastySpaceApple:爲什麼mongodb標籤? –
那麼這3個monngo文件是你想要轉換的,在這種情況下,12?正在使用任何特定的語言?或者它是mongo控制檯? – xcorat