34,837
社区成员




存储过程,视图不可以。
看错了,modify。
declare @sql varchar(8000)
set @sql = 'select c.部门名称 部门,count(*) 合计 '
select @sql = @sql + ' , sum(case 职称 when ''' + 职称 + ''' then 1 else 0 end) [' + 职称 + ']'
from (select distinct 职称 from 职称表 ) as a
set @sql = @sql + ' from 主表 b left join 部门表 c on c.部门=b.部门 group by b.部门 order by b.部门'
exec(@sql)
--加上部门名称
declare @sql varchar(8000)
set @sql = 'select c.部门名称 部门,(select count(1) from 主表 where 部门=b.部门) 合计 '
select @sql = @sql + ' , max(case 职称 when ''' + 职称 + ''' then 职称 else '''' end) [' + 职称 + ']'
from (select distinct 职称 from 职称表 ) as a
set @sql = @sql + ' from 主表 b left join 部门表 c on c.部门=b.部门 group by b.部门 order by b.部门'
exec(@sql)
create table 主表 (姓名 varchar(10), 部门 varchar(10), 学历 varchar(10), 职称 varchar(10))
insert into 主表 values('张三' , '部门3' , '大专' , '中级')
insert into 主表 values('李四' , '部门1' , '大专' , '初级')
insert into 主表 values('王五' , '部门2' , '大专' , '初级')
insert into 主表 values('马六' , '部门9' , '大专' , '高级')
insert into 主表 values('赵七' , '部门2' , '大专' , '中级')
insert into 主表 values('周八' , '部门2' , '大专' , '中级')
create table 部门表 (部门 varchar(10))
insert into 部门表 values('部门1')
insert into 部门表 values('部门2')
insert into 部门表 values('部门3')
insert into 部门表 values('部门9')
create table 职称表 (职称 varchar(20))
insert into 职称表 values('初级')
insert into 职称表 values('中级')
insert into 职称表 values('高级')
insert into 职称表 values('超级')
insert into 职称表 values('超超超超高级')
go
--sql 2000的动态SQL.
declare @sql varchar(8000)
set @sql = 'select t1.部门 , count(*) 合计 '
select @sql = @sql + ' , sum(case t2.职称 when ''' + 职称 + ''' then 1 else 0 end) [' + 职称 + ']'
from (select distinct 职称 from 职称表) as a
set @sql = @sql + ' from 部门表 t1 left join 主表 t2 on t1.部门 = t2.部门 group by t1.部门'
exec(@sql)
drop table 主表,部门表,职称表
/*
部门 合计 超超超超高级 超级 初级 高级 中级
---------- ----------- ----------- ----------- ----------- ----------- -----------
部门1 1 0 0 1 0 0
部门2 3 0 0 1 0 2
部门3 1 0 0 0 0 1
部门9 1 0 0 0 1 0
*/
declare @sql varchar(8000)
set @sql = 'select 部门,(select count(1) from 主表 where 部门=b.部门) 合计 '
select @sql = @sql + ' , max(case 职称 when ''' + 职称 + ''' then 职称 else '''' end) [' + 职称 + ']'
from (select distinct 职称 from 职称表 ) as a
set @sql = @sql + ' from 主表 b group by 部门 order by 部门'
exec(@sql)
--sql 2000的动态SQL.
declare @sql varchar(8000)
set @sql = 'select t1.部门 '
select @sql = @sql + ' , sum(case t1.职称 when ''' + 职称 + ''' then 1 else 0 end) [' + 职称 + ']'
from (select distinct 职称 from 职称表) as a
set @sql = @sql + ' , count(*) 合计 from 部门表 left join 主表 t2 on t1.部门 = t2.部门 group by t1.部门'
exec(@sql)