我有下表
ID-----Name------Value
1 City New York
1 Country USA
2 City Barcelona
2 Country Spain
所需的查询输出
ID------City-------Country
1 New York USA
2 Barcelona Spain
如果可以使用Oracle中的查询实现这一点,请告诉我。我遇到了两个概念listagg和pivote但却无法理解如何使用它们来实现我的需要。
我使用listagg以一种方式获得结果,但是所有列都在单列中,我需要将其分开。
select ID,
listagg(Name||';'||Value, ',') within group (order by Name) as Criteria
from table_name
group by ID;
答案 0 :(得分:3)
我会使用聚合来做到这一点:
select id, max(case when name = 'City' then value end) as city,
max(case when name = 'Country' then value end) as country
from t
group by id;
答案 1 :(得分:3)
使用PIVOT
:
Oracle 11g R2架构设置:
CREATE TABLE countries ( ID, Name, Value ) AS
SELECT 1, 'City', 'New York' FROM DUAL UNION ALL
SELECT 1, 'Country', 'USA' FROM DUAL UNION ALL
SELECT 2, 'City', 'Barcelona' FROM DUAL UNION ALL
SELECT 2, 'Country', 'Spain' FROM DUAL;
查询1 :
SELECT *
FROM countries
PIVOT ( MAX( value ) FOR name IN ( 'City' AS City, 'Country' AS Country ) )
<强> Results 强>:
| ID | CITY | COUNTRY |
|----|-----------|---------|
| 1 | New York | USA |
| 2 | Barcelona | Spain |