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.
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.
- username| user_group1| user_group2| user_group3 |user_group4 |user_group5
- --------|------------|------------|-------------|------------|------------
- | | | | |
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.
- SELECT usr.usr_username ,
- MAX(CASE WHEN RN=1 THEN gr_role_name ELSE NULL END) group1,
- MAX(CASE WHEN RN=2 THEN gr_role_name ELSE NULL END) group2,
- MAX(CASE WHEN RN=3 THEN gr_role_name ELSE NULL END) group3,
- MAX(CASE WHEN RN=4 THEN gr_role_name ELSE NULL END) group4,
- MAX(CASE WHEN RN=5 THEN gr_role_name ELSE NULL END) group5,
- FROM (
- SELECT usr.usr_username,grp.gr_role_name,
- ROW_NUMBER() OVER (PARTITION BY gr_role_name ORDER BY gr_role_name) AS rn FROM adm_users usr, adm_user_groups grp
- WHERE user.usr_username=grp.grp_usr_username
- )
- WHERE RN<=5
- GROUP BY usr_username;
- Output
- --------
- username| user_group1| user_group2| user_group3 |user_group4 |user_group5
- --------|------------|------------|-------------|------------|------------
- scott |admin |developer |billing |approver |
- tom |admin |developer |billing |accounting | Others
No comments:
Post a Comment