2

I have the following example table (simplified from what I really have as there are a few more joins in there)

|permission|username|
| perm1    | u1     |
| perm2    | u1     |
| perm3    | u1     |
| perm1    | u2     |
| perm4    | u2     |

I have many users and many groups in this table

I am having trouble with user permissions where some users can do things in my application and others cannot. At the moment I am having to manually go through and figure out what the differences are.

I want to crate a query from the above table that gives me an answer like this

|permission| u1 | u2 |
|perm1     | 1  | 1  |
|perm2     | 1  | 0  |
|perm3     | 1  | 0  |
|perm4     | 0  | 1  |

I do not really want 1 and 0 under the users but I want something to I can easily visualise that user 1 has these permissions and user2 does not. This would be really useful for me to ensure that users have the same permissions.

I have done the SQL to get the top table so I can see the permissions.

I was thinking that some sort of left join on itself might the answer there but everything I try seems to end up as invalid SQL.

Any hints please? Im happy to experiment if I get a starting point :)

Thanks in advance

4

1 回答 1

3

您正在寻找的内容称为“枢轴”。一种方法是使用group by,例如:

select  permission
,       count(case when username = 'u1' then 1 end) as User1
,       count(case when username = 'u2' then 1 end) as User2
,       count(case when username = 'u3' then 1 end) as User3
,       ...
from    YourTable
group by
        permission

看起来Oracle支持PIVOT关键字。你可以用它来完成同样的事情:

select  *
from    YourTable
pivot   (
        count(*) as HasPermission
        for (username) in ('u1', 'u2', 'u3', ...)
        );

SQL Fiddle 上两种方法的示例。

于 2013-05-26T19:36:42.487 回答