0

我有以下数据的福利表

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
4

1 回答 1

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

于 2012-10-09T10:50:26.950 回答