2

I have the below table

ID-----Name------Value
1      City      New York
1      Country   USA
2      City      Barcelona
2      Country   Spain

Desired query output is

ID------City-------Country
1       New York   USA
2       Barcelona  Spain

Could you please let me know if this can be achieved using a query in Oracle. I came across two concepts listagg and pivote but not able to understand how to use those to achieve what I need.

I am getting the result in one way using listagg with the below query but all columns are coming in single column which I need to separate out.

select ID, 
       listagg(Name||';'||Value, ',') within group (order by Name) as Criteria
from table_name
group by ID; 

2 Answers 2

3

I would do it using aggregation:

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the quick response Gordon Linoff, this fulfills the purpose I am looking for. Also can you please explain the reason of having max for my better understanding.
@Vinay . . . It is needed for the group by. There should only be one value, so the max() just chooses it.
3

Use PIVOT:

SQL Fiddle

Oracle 11g R2 Schema Setup:

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;

Query 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 |

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.