我不知道问题的标题是否足够清楚,但我有这种情况:
TABLE ID, VALUE_1, VALUE_2
1, HORSE , 500
1, DOG , 400
1, DUCK , 300
2, HORSE , 500
2, DOG , 400
2, DUCK , 300
我想查看
之类的值ID HORSE DOG DUCK
1 500 400 300
2 500 400 300
答案 0 :(得分:1)
您可以使用条件聚合:
select id,
sum(case when value_1 = 'HORSE' then value_2 end) as horse,
sum(case when value_1 = 'DOG' then value_2 end) as dog,
sum(case when value_1 = 'DUCK' then value_2 end) as duck
from t
group by id
order by id;
答案 1 :(得分:1)
使用condititonal aggregation
select id,
max(case when value_1 = 'HORSE' then value_2 end ) as horse,
max(case when value_1 = 'DOG' then value_2 end ) as dog,
max(case when value_1 = 'DUCK' then value_2 end ) as duck
from tab
group by id;
答案 2 :(得分:1)
有条件聚合:
select
ID,
max(case when value_1 = 'HORSE' THEN value_2 end) HORSE,
max(case when value_1 = 'DOG' THEN value_2 end) DOG,
max(case when value_1 = 'DUCK' THEN value_2 end) DUCK
from tablename
group by ID
答案 3 :(得分:0)
在Oracle 11.1和更高版本中,可以使用PIVOT
运算符。假设表名称为T
:
select id, horse, dog, duck
from t
pivot (min(value_2)
for value_1 in ('HORSE' as horse, 'DOG' as dog, 'DUCK' as duck))
order by id
;
在Oracle 12.1和更高版本中,可以使用MATCH_RECOGNIZE
实现相同的功能(并且我们不再需要聚合):
select id, horse, dog, duck
from t
match_recognize(
partition by id
measures horse.value_2 as horse,
dog.value_2 as dog,
duck.value_2 as duck
pattern ( (horse|dog|duck)* )
define horse as value_1 = 'HORSE', dog as value_1 = 'DOG',
duck as value_1 = 'DUCK'
);