SQL Server: group result

bxfogqkk  于 2023-06-21  发布在  SQL Server
关注(0)|答案(1)|浏览(162)

I have data in a SQL Server 2016 table and I want output as shown below:

So basically I have all databases as column names (DYNAMIC - so the number of columns i.e. database names can increase/decrease) and in the user_name column, I have a list of all groups and members.

However, the group displays its permission level on a particular database column to which the group belongs.

I want to display only members of the group in the output along with its groupname and permission level on the database same as the group had.

Sample table script:

CREATE TABLE dbo.test
(
    Sequence bigint identity(1,1) not null,  
    user_name nvarchar(100),
    LoginType varchar(50),
    [master] varchar(50),
    [tempdb] varchar(50),
    BI_SOPS varchar(50),
    BI_PSO varchar(50),
    BI_SUP varchar(50),
    BI_FIN varchar(50),
    BI_EDU varchar(50),
    groupname nvarchar(100),
    DBName varchar(50)
);

INSERT INTO dbo.test (user_name ,LoginType, master ,tempdb ,BI_SOPS ,BI_PSO ,BI_SUP ,BI_FIN,BI_EDU,groupname,DBName  )
VALUES ('VINX\SqlServer_FIN','WINDOWS_GROUP',NULL,NULL,NULL,NULL,NULL,'db_datareader',NULL,NULL,NULL),
('TR\u1','WINDOWS_GROUP- User',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'VINX\SqlServer_FIN','BI_FIN'),
('TR\u2','WINDOWS_GROUP- User',NULL,NULL,NULL,NULL,NULL,NULL,NULL,'VINX\SqlServer_FIN','BI_FIN');

SELECT * FROM dbo.test;

DBFiddle

ckocjqey

ckocjqey1#

It's not clear what your problem is. Try this

with gr as(
select *
from test
where LoginType='WINDOWS_GROUP'
)
select t.sequence,t.user_name,t.LoginType --,g.user_name,t.groupname
  ,case when g.DBName is not null then g.DBName else t.DBName end master
  ,case when g.tempdb is not null then g.tempdb else t.tempdb end tempdb
  ,case when g.BI_SOPS is not null then g.BI_SOPS else t.BI_SOPS end BI_SOPS
  ,case when g.BI_PSO is not null then g.BI_PSO else t.BI_PSO end BI_PSO
  ,case when g.BI_SUP is not null then g.BI_SUP else t.BI_SUP end BI_SUP
  ,case when g.BI_FIN is not null then g.BI_FIN else t.BI_FIN end BI_FIN    
  ,case when g.BI_EDU is not null then g.BI_EDU else t.BI_EDU end BI_EDU
from test t left join gr g on g.user_name=t.groupname
where t.LoginType<>'WINDOWS_GROUP'

相关问题