You did not specify what RDBMS you are using - so here are solutions for both MySQL and SQL Server.
MySQL:
This is a PIVOT
but MySQL does not have a PIVOT
function so you will need to replicate it using an aggregate function and a CASE
statement.
Static Version - is where you know all of the values beforehand:
select role,
sum(case when permission = 'p1' then 1 else 0 end) p1,
sum(case when permission = 'p2' then 1 else 0 end) p2,
sum(case when permission = 'p3' then 1 else 0 end) p3
from yourtable
group by role;
See SQL Fiddle with Demo
If you don't know the values to turn to column beforehand then you can use a prepared statement:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when permission = ''',
permission,
''' then 1 else 0 end) AS ',
permission
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT role, ', @sql, '
FROM yourtable
GROUP BY role');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with Demo
SQL Server:
There is a PIVOT
function in sql server and you can either hard-code the values or use dynamic sql.
Static Version:
select *
from
(
select role, permission
from yourtable
) src
pivot
(
count(permission)
for permission in ([p1], [p2], [p3])
) piv;
See SQL Fiddle with Demo
Dynamic Version:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(permission)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT role, ' + @cols + ' from
(
select role, permission
from yourtable
) x
pivot
(
count(permission)
for permission in (' + @cols + ')
) p '
execute(@query)
See SQL Fiddle with Demo
The result from all versions is:
| ROLE | P1 | P2 | P3 |
-----------------------
| r1 | 1 | 0 | 0 |
| r2 | 1 | 1 | 0 |
| r3 | 1 | 1 | 1 |