22,209
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据: [bb]
if object_id('[bb]') is not null drop table [bb]
go
create table [bb] (privid int,moduid varchar(4),operid varchar(6))
insert into [bb]
select 1,'01','view' union all
select 2,'0101','add' union all
select 3,'0101','select' union all
select 4,'02','view' union all
select 5,'0201','add' union all
select 6,'0201','select' union all
select 7,'0201','delete'
select
moduid=left(moduid,2),
[add]=sum([add]),
[select]=sum([select]),
[delete]=sum([delete])
from [bb]
pivot
(
count(operid)
for operid in ([add],[select],[delete])
)t
group by left(moduid,2)
moduid add select delete
------ ----------- ----------- -----------
01 1 1 0
02 1 1 1
(2 行受影响)
select moduid,
[add] = select count(*) from p where p.moduid = t.moduid and operid = 'add'
[select] = select count(*) from p where p.moduid = t.moduid and operid = 'select',
[delete] = select count(*) from p where p.moduid = t.moduid and operid = 'delete'
from p t group by moduid
create table tb(privid int,moduid varchar(10),operid varchar(10))
insert into tb values(1 ,'01' ,'view')
insert into tb values(2 ,'0101' ,'add')
insert into tb values(3 ,'0101' ,'select')
insert into tb values(4 ,'02' ,'view')
insert into tb values(5 ,'0201' ,'add')
insert into tb values(6 ,'0201' ,'select')
insert into tb values(7 ,'0201' ,'delete')
go
select * from (select left(moduid,2) moduid , operid from tb) a pivot (max(operid) for operid in ([add],[select],[delete])) b
drop table tb
/*
moduid add select delete
------ ---------- ---------- ----------
01 add select NULL
02 add select delete
(2 行受影响)
*/