Skip to Main Content
  • Questions
  • Merge Two Rows Into One Row With 2 Columns

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Brian.

Asked: August 08, 2018 - 9:44 pm UTC

Last updated: August 09, 2018 - 9:27 am UTC

Version: 11.2.0.4

Viewed 10K+ times! This question is

You Asked

Is there a way to simply merge via a single pivot or analytical query the results from two rows into one? We have a legacy table that is essentially storing key value pairs in columnar format. As an test case, here is an example:

create table kvtest ( App_ID Number, User_Id Number, strKey varchar2(10), strValue varchar2(20));

insert into kvtest select 1, 100, 'Color', 'Blue' from dual;
insert into kvtest select 1, 200, 'Location', 'USA' from dual;
commit;


The output of select * from kvtest:
    APP_ID    USER_ID STRKEY     STRVALUE            
---------- ---------- ---------- --------------------
         1        200 Location   USA                 
         1        100 Color      Blue      


I'd like to combine key:values by an app_id regardless of the user_id which in this example will always be limited to 2 rows (meaning there will not be 3 user_ids per app_id, only 2).

My desired output would look like this:
    APP_ID LOCATION                         COLOR                           
---------- -------------------------------- ------------
         1 USA                              Blue       


Thanks!

and Chris said...

Sure. Pivot will help you here.

- In a subquery select the columns that you want in your output or will pivot by (the database will implicitly group by columns NOT in the pivot)
- Then list out the keys you want to become columns in the pivot clause:

with rws as (
  select app_id, strkey, strvalue from kvtest
)
  select * from rws
  pivot ( 
    min ( strvalue ) for strkey in (
      'Color' color, 'Location' location
    )
  );

APP_ID   COLOR   LOCATION   
       1 Blue    USA   


If you want to know more about pivoting, read: https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-back-again-with-sql-aka-pivot-and-unpivot

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Brian Lucas, August 09, 2018 - 3:01 pm UTC


More to Explore

SQL

The Oracle documentation contains a complete SQL reference.