This post outlines basic usage of Oracle’s pivot function in sql.
Requirement was to create a list of granted roles that can be exported to Excel sheet. The list would contain One user per record and each column would list few (predefined) roles assigned to user.
First thing that came to mind was decode function, but the way I was using it: listed one record for each role that was granted to a user. For example, the output looked like:
USERNAME RESOURCE DBA ------------------------------ --------------- ---------- SCOTT YES NO SCOTT NO YES
Since the requirement is to have one row per user, we needed to transpose the ‘granted_role’ column of dba_role_privs. For this, Pivot function provided by Oracle (starting 11g) serves the purpose. So, using pivot function, query was changed to something like this:
select * from (
select username, granted_role
from dba_role_privs r, dba_users u where
u.username=r.grantee(+)
and u.username not in ('SYS','SYSTEM','DBSNMP','ORACLE_OCM','CTXSYS'))
pivot
(
count(granted_role)
for granted_role in ('RESOURCE','DATAPUMP_EXP_FULL_DATABASE','EXP_FULL_DATABASE','DATAPUMP_IMP_FULL_DATABASE','DBA','IMP_FULL_DATABASE')
) order by username;
Output for SCOTT user:
USERNAME 'RESOURCE' 'DATAPUMP_EXP_FULL_DATABASE' 'EXP_FULL_DATABASE' 'DATAPUMP_IMP_FULL_DATABASE' 'DBA' 'IMP_FULL_DATABASE' ----------- ---------- ---------------------------- ------------------- ---------------------------- ----- ------------------- SCOTT 1 0 0 0 1 0
Only aggregate functions can be used as an argument to Pivot function. That is the reason count(granted_role) was performed. This works perfectly in our case because the count would be either 1 or 0 (always) depending upon if a role is granted or not.
It is indeed possible to lower high blood pressure by only
taking herbal medicines and vitamins and eating certain foods that can lower high blood pressure.
Crowe, The Tony Rice Unit, Chesapeake and Aldridge, and Bennett & Gaudreau) on mandolin and mandola, Tony Williamson
(mandolin), Chris Brashear (fiddle), and Tom Corbett (mandolin).
At the end of the meeting it was announced that he was to enroll in a dental college.
The following year, at the age of thirty-eight, he matriculated at the Louisville Dental College in Kentucky, where he
remained until he was graduated. Members of the press and/or other interested parties may obtain more information about this practice and/or the content of this press
release by contacting the following: Fayette Chiropractic Center Dr.
Comment by Louanne — April 20, 2013 @ 12:32 pm