Friday, 26 May 2017

Converting N Rows into 1 Rown N Columns

The below example gives you an idea on how to Convert N rows of data into 1 row N Column. 
The busniess requirement says, "Pull out the list of application users and the corresponding groups they belongs".

Assume each users belongs to 4 to 5 different groups.  The output contains only one record for each row. The output format is something linke this. 

  1. username| user_group1| user_group2| user_group3 |user_group4 |user_group5  
  2. --------|------------|------------|-------------|------------|------------  
  3.         |            |            |             |            |   

user details are stored in adm_users and the group/role details are stored in adm_user_groups. These two tables need to be joined. The query is given below. 

  1. SELECT  usr.usr_username ,  
  2. MAX(CASE WHEN RN=1 THEN gr_role_name ELSE NULL END)    group1,  
  3. MAX(CASE WHEN RN=2 THEN gr_role_name ELSE NULL END)    group2,  
  4. MAX(CASE WHEN RN=3 THEN gr_role_name ELSE NULL END)    group3,  
  5. MAX(CASE WHEN RN=4 THEN gr_role_name ELSE NULL END)    group4,  
  6. MAX(CASE WHEN RN=5 THEN gr_role_name ELSE NULL END)    group5,  
  7. FROM (  
  8. SELECT  usr.usr_username,grp.gr_role_name,  
  9. ROW_NUMBER() OVER (PARTITION BY gr_role_name ORDER BY gr_role_name) AS rn FROM adm_users usr, adm_user_groups grp   
  10. WHERE  user.usr_username=grp.grp_usr_username  
  11. )  
  12. WHERE RN<=5  
  13. GROUP BY usr_username;  
  14.   
  15. Output  
  16. --------  
  17.   
  18. username| user_group1| user_group2| user_group3 |user_group4 |user_group5  
  19. --------|------------|------------|-------------|------------|------------  
  20. scott   |admin       |developer   |billing      |approver    |  
  21. tom     |admin       |developer   |billing      |accounting  | Others

No comments:

Post a Comment