oracle 使用联接和选择语句显示列

lskq00tm  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(176)

我在尝试将多行合并合并为一行。下面是一个例子。我的实际数据有更多的行和更多的列,但我已经压缩了它。我也只需要包括某些行/列。我遇到的问题是,如果我可以把行变成列,它仍然显示不应该在那里的额外行。
这是我得到的,如果我SELECT * FROM Employees
| ID|轮廓|优先|位置|委员会|审查|
| --|--|--|--|--|--|
| 远程|主管| 0 |明尼苏达|N| N|
| 远程|主管| 3 |纽约|N| N|
| 远程|经理| 0 |佛蒙特|Y| N|
| 远程|经理| 0 |爱荷华州|N| Y|
| 远程|经理| 0 |怀俄明州|N| N|
| 远程|经理| 3 |爱荷华州|N| N|
| 远程|经理|L|爱荷华州|Y| N|
| 远程|工人| 0 |佛蒙特|Y| N|
| 远程|工人| 0 |爱荷华州|N| Y|
| 远程|工人| 0 |怀俄明州|N| N|
| 远程|工人| 1 |爱荷华州|N| N|
| 远程|工人| 3 |爱荷华州|N| N|
| 远程|领导人| 1 |爱荷华州|N| N|
| 远程|领导人| 2 |俄勒冈州|N| N|
我想要的是一行的经理和另一行的工人和其余的信息列(我需要经理和工作概况。优先级0 &远程ID的位置和佣金列)
| 轮廓|位置|委员会|位置|委员会|位置|委员会|
| --|--|--|--|--|--|--|
| 经理|佛蒙特|Y|爱荷华州|N|怀俄明州|N|
| 工人|佛蒙特|N|爱荷华州|N|怀俄明州|Y|
我已经让这个查询在一个小规模的表中工作,表中的信息非常少,但它不能在更大的规模上工作。我猜这是因为我没有正确地告诉我的查询包括/排除什么,但我似乎不能弄清楚。

SELECT EE.ID, EE.Profile, vtm.Location, vtm.Commissions, iam.Location, iam.Commissions, wmm.Location, wmm.Commissions
FROM Employees EE
Left OUTER JOIN
    (SELECT ID, Profile, Location, Commissions FROM Employees WHERE Location = 'Vermont' AND Profile      = 'Manager') vtm
    ON EE.ID = vtm.ID
Left OUTER JOIN
    (SELECT ID, Profile, Location, Commissions FROM Employees WHERE Location = 'Iowa' AND Profile =   'Manager') iam
    ON vtm.ID = iam.ID
Left OUTER JOIN
    (SELECT ID, Profile, Location, Commissions FROM Employees WHERE Location = 'Wyoming' AND Profile = 'Manager') wmm
    ON iam.ID = wmm.ID
WHERE EE.ID = 'Remote' AND Priority = '0'
vxf3dgd4

vxf3dgd41#

您可以使用条件聚合来获得此结果:

select
  profile,
  'Vermont' as location_1,
  max(case when location = 'Vermont' then commissions end) as commissions_1,
  'Iowa' as location_2,
  max(case when location = 'Iowa' then commissions end) as commissions_2,
  'Wyoming' as location_3,
  max(case when location = 'Wyoming' then commissions end) as commissions_3
from employees
where profile in ('Manager', 'Worker') and id = 'Remote' and priority = '0'
group by profile
order by profile;

当然,您可以将位置设置为commissions标题,而不是让所有行都显示相同位置的列:

select
  profile,
  max(case when location = 'Vermont' then commissions end) as vermont,
  max(case when location = 'Iowa'    then commissions end) as iowa,
  max(case when location = 'Wyoming' then commissions end) as wyoming
from employees
where profile in ('Manager', 'Worker') and id = 'Remote' and priority = '0'
group by profile
order by profile;

解决这个问题的另一个选择是PIVOT子句。

相关问题