将列有效地转换为行

时间:2013-12-22 22:41:13

标签: mysql unpivot

你能帮我解决这个项目吗?我研究过先前提出的问题,但他们似乎没有解决这种独特的情况。

示例数据:

 Member |    DOS    |  Dx1   |  Dx2  |  Dx3  | Dx4  | Dx5
 12345  | 1/1/2011  | 12142  | 12345 | 65657 | 5657 | 568
 56484  | 3/5/2011  | 568    | 56785 | 5695  | 575  | 168
 56872  | 2/12/2011 | 567    | 567   |

我需要看到的是:

 Member DOS DX Seq
 12345 1/1/2011 12142 Dx1
 12345 1/1/2011 12345 Dx2
 12345 1/1/2011 65657 Dx3

等等。只显示那些不为空的Dx-因此对于56872,我们只看到Dx1和Dx2,但对于其他2,我们会看到所有5个Dx的记录。

有人能帮助我吗?  谢谢。

1 个答案:

答案 0 :(得分:0)

此类数据转换称为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。此方法将为您提供结果,但在较大的表上可能效率不高。

另一种方法是在虚拟桌面上使用CROSS 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 |
相关问题