Oracle临时表报告创建

时间:2015-04-02 15:31:58

标签: oracle

临时表格报告创建

用户表

User id  User name 
1         user1
2         user2
3         user3  

USER_IN_ROLES表

USRINR_USER_ID   USRINR_ROLES_ID

1                        103
3                        104
2                        105
1                        107
2                        108
1                        105
1                        108

角色rl

Roles ID                 Description
104                      User management
107                      Modify
103                      Debit
105                      General
108                      Audit

表1和表1之间的关系用户ID 2和角色ID介于2和2之间3

我想要一个像这样的操作的查询

UName   FirstEntitl     Second Entitl
user1    Team           Debit
user3   Security admin  User Management
user2   Read only user  General
user1   Team            Modify
user2   Read only user  Audit
user1   Team            General
user1   Team            Audit

因此,所有具有用户管理角色(没有其他角色)的用户都将是安全管理员具有修改角色的用户将是团队,如果用户没有修改,则用户管理是只读用户。用户1是TEAM,所以当他有另一项权利时,仍然第2栏应该让他作为团队。如果用户具有修改,则用户的所有其他行应具有团队。 USer是Reead唯一的用户,因为他在任何地方都没有修改。用户3很容易,如果他有用户管理,他就是Sec Admin。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,我认为这个简单的查询会做到这一点

SELECT  a.user_name as UName,
        decode(count_of_roles.nbRoles,
               1, decode(b.id,
                        107, 'Team', -- Display team as it is the only role
                        104, 'Security admin', -- Display Security admin as it is the only role
                        'Read only user'), -- If only one role was found, but neither team or admin we display Read only user 
               'Read only user') as "First Entitl", -- Display Read only user if more then one role was found
        c.description as "Second Entitl"
FROM users a
JOIN users_in_roles b on a.user_id = b.usrinr_user_id
JOIN roles_rl c on c.roles_id = b.usrinr_roles_id
JOIN (SELECT a.user_id, count(b.usrinr_roles_id) as nbRoles -- Join on a result set giving the nb of roles for the current user.
       FROM users a
       JOIN user_in_roles b ON a.user_id = b.usrinr_roles_id
       GROUP BY a.user_id) count_of_roles ON a.user_id = count_of_roles.user_id;