将行数据转换为不同的列

时间:2012-10-09 10:44:06

标签: oracle plsql pivot

我有以下数据的福利表

id    |     Name
----------------
1     |  Shopping 
2     |  Travel 
3     |  Fuel 
4     |  Lifestyle 
5     |  Airline 
6     |  Entertainment 
7     |   Golf 

我还有另一个名为Plan的表,其中包含以下数据

Plan_id   Benefit_id
---------------------
101      |      1
101      |      2
101      |      3
102      |      2
102      |      4
102      |      6
102      |      1
103      |      7 
103      |      1
104      |      4
104      |      5

现在,我想使用以下表格显示数据。

Plan_id |  Shopping |Travel |Fuel  |Lifestyle  |Airline    |Entertainment|Golf
---------------------------------------------------------------------------------
101     |  yes      | yes   |  yes |   no      | no        | no          | no
102     |  yes      | yes   |  no  |   yes     | no        | yes         | no
103     |  yes      | no    |  no  |   no      | no        | no          | no
104     |  no       | no    |  no  |   yes     | yes       | no          | no

1 个答案:

答案 0 :(得分:3)

如果没有看到完整的表结构或任何示例数据,您可以使用以下内容与聚合函数和CASE语句:

select 
  max(case when BENEFIT_CAT_NAME = 'Shopping' then value end) as Shopping,
  max(case when BENEFIT_CAT_NAME = 'Travel' then value end) as Travel,
  max(case when BENEFIT_CAT_NAME = 'Fuel' then value end) as Fuel,
  max(case when BENEFIT_CAT_NAME = 'Lifestyle' then value end) as Lifestyle,
  max(case when BENEFIT_CAT_NAME = 'Airline' then value end) as Airline,
  max(case when BENEFIT_CAT_NAME = 'Entertainment' then value end) as Entertainment
from yourtable

或者,根据您的Oracle版本,您可以使用PIVOT函数:

select *
from 
(
  select BENEFIT_CAT_NAME, value
  from yourtable
) x
pivot
(
  max(value)
  from BENEFIT_CAT_NAME in('Shopping', 'Travel', 'Fuel', 
                           'Lifestyle', 'Airline', 'Entertainment')
) p

编辑,根据您的表格结构和数据,您可以使用以下内容:

select p.plan_id,
  max(case when b.name = 'Shopping' then 'yes' else 'no' end) Shopping,
  max(case when b.name = 'Travel' then 'yes' else 'no' end) Travel,
  max(case when b.name = 'Fuel' then 'yes' else 'no' end) Fuel,
  max(case when b.name = 'Lifestyle' then 'yes' else 'no' end) Lifestyle,
  max(case when b.name = 'Airline' then 'yes' else 'no' end) Airline,
  max(case when b.name = 'Entertainment' then 'yes' else 'no' end) Entertainment,
  max(case when b.name = 'Golf' then 'yes' else 'no' end) Golf
from plan p
left join benefit b
  on p.benefit_id = b.id
group by p.plan_id
order by p.plan_id;

请参阅SQL Fiddle with Demo