Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 chowing 1 dimensional data to 2 dimensional form

Author  Topic 

sheriefes
Starting Member

9 Posts

Posted - 2012-05-14 : 02:49:46
Hi
I am using Netframework 3.5 and Sql Server 2005
I have 2 tables- part of a web application table structure and sample data as follows
1.  permissions(permissionId, permission)
1  SALES
2 PURCHASES
3 SALES RETURN
4 HR MANAGEMENT
2.  userPermissions(userId,permissionId)
userId   permissionId
aa         2    - means user aa has permission to access sales page
aa         4
bb         1
bb         2     as another example,  bb has permission to access purchase page
cc         4        

and so son
I want show the above data as 2-dimensionl information, as below
Permission                            aa              bb                  cc
SALES                                                     Y
PURCHASES                          Y               Y
SALES RETURN
HR MANAGEMENT                  Y                                      Y

vinu.vijayan
Posting Yak Master

227 Posts

Posted - 2012-05-14 : 03:24:50
This will do it for you:

--Creating Tables

Create Table Permission
(permissionId int, permission varchar(20))

Create Table UserPermissions
(userId varchar(2),
permissionId int)


--Inserting Sample Data into Tables

Insert Into Permission
Select 1, 'SALES'
union ALL
Select 2, 'PURCHASES'
union ALL
Select 3, 'SALES RETURN'
union ALL
Select 4, 'HR MANAGEMENT'

Insert Into UserPermissions
Select 'aa', 2 -- means user aa has permission to access sales page
Union ALL
Select 'aa', 4
Union ALL
Select 'bb', 1
Union ALL
Select 'bb', 2 --as another example, bb has permission to access purchase page
Union ALL
Select 'cc', 4


--Query for your Requirement

Select a.Permission,
Max(Case When b.UserId = 'aa' Then 'Y' Else '' End) as aa,
Max(Case When b.UserId = 'bb' Then 'Y' Else '' End) as bb,
Max(Case When b.UserId = 'cc' Then 'Y' Else '' End) as cc
From Permission as a
Full JOIN UserPermissions as b on a.permissionId = b.permissionId
Group By a.permission


N 28° 33' 11.93148"
E 77° 14' 33.66384"
Go to Top of Page
   

- Advertisement -