Saturday 4 March 2017

PL/SQL: Some helpful SQL queries -2

Continuation of PL/SQL: Some helpful SQL queries -1

#7. How to convert Multiple Columns into Rows (Unpivot multiple columns). 
Source Data


Expected output

 with t as  
 (select '1001' emp_no,'Anoop' emp_first_name, 'Johny' emp_last_name
        ,'Developer' job_role, 'Senior Developer' new_job_role  
        ,'150000'    salary  , '175000'           new_salary 
        ,'Australia' country , 'Australia'        new_country  
  from dual  
  union  
  select '1002' emp_no,'Sajeer' emp_first_name, 'Omar' emp_last_name
       ,'Senior Developer' job_role, 'Developer' new_job_role  
       ,'105000'           salary  , '100000'    new_salary 
       ,'Australia'        country , 'Australia' new_country   
  from dual  
 )
 select (case when row_number() over (partition by emp_no order by emp_no ) = 1    
              then emp_no   
         end) emp_no  
       ,(case when row_number() over (partition by emp_no order by emp_no ) = 1    
              then emp_first_name   
         end) emp_first_name  
       ,(case when row_number() over (partition by emp_last_name order by emp_no ) = 1    
              then emp_last_name   
         end) emp_last_name   
       ,col     detail  
       ,val     old_value  
       ,new_val new_value  
 from t    
 unpivot include nulls ((val,new_val) for col in ((job_role,new_job_role) as 'Job Role'  
                                                 ,(salary,new_salary)     as 'Salary'  
                                                 ,(country,new_country)   as 'Country'));  

Refer:
PIVOT and UNPIVOT Operators in Oracle Database 11g Release 
Pivot and Unpivot


Feel free to point out if anything is missing/wrong in this blog.

No comments:

Post a Comment