declare @s varchar(8000) set @s='' select @s=@s+',['+workname+']=sum(case workname when '''+workname+''' then 1 else 0 end)' from [table] group by workname exec('select 性别=sex'+@s+' from [table] group by sex')
--测试--测试数据 create table [table](name varchar(10),workname varchar(10),sex varchar(10)) insert [table] select '汪娜' ,'计供科','女' union all select '凌开明','技术科1','男' union all select '周寅' ,'质监科','男' union all select '朱荷波','八车间','男' union all select '邬静娜','八车间','女' union all select '钱丹萍','八车间','女' union all select '杜丽娟','三车间','女' union all select '毛易耀','三车间','男' union all select '王仲秋','四车间','男' go--查询 declare @s varchar(8000) set @s='' select @s=@s+',['+workname+']=sum(case workname when '''+workname+''' then 1 else 0 end)' from [table] group by workname exec('select 性别=sex'+@s+' from [table] group by sex') go--删除测试 drop table [table]/*--测试结果性别 八车间 计供科 技术科1 三车间 四车间 质监科 ----- ------ ------- ------- ------- ------ -------- 男 1 0 1 1 1 1 女 2 1 0 1 0 0 --*/
declare @s varchar(8000) set @s='' select @s=@s+',['+workname+']=sum(case workname when '''+workname+''' then 1 else 0 end)' from [table] group by workname exec('select 性别=sex'+@s+' from( select name,workname,sex from [table] union all select name,workname,zhenzhi from [table] union all select name,workname,zhichen from [table] union all select name,workname,xueli from [table] )a group by sex') go
create table [table](name varchar(10),workname varchar(10),sex varchar(10))
insert [table] select '汪娜' ,'计供科','女'
union all select '凌开明','技术科1','男'
union all select '周寅' ,'质监科','男'
union all select '朱荷波','八车间','男'
union all select '邬静娜','八车间','女'
union all select '钱丹萍','八车间','女'
union all select '杜丽娟','三车间','女'
union all select '毛易耀','三车间','男'
union all select '王仲秋','四车间','男'
go--查询
declare @s varchar(8000)
set @s=''
select @s=@s+',['+workname+']=sum(case workname when '''+workname+''' then 1 else 0 end)'
from [table]
group by workname
exec('select 性别=sex'+@s+'
from [table]
group by sex')
go--删除测试
drop table [table]/*--测试结果性别 八车间 计供科 技术科1 三车间 四车间 质监科
----- ------ ------- ------- ------- ------ --------
男 1 0 1 1 1 1
女 2 1 0 1 0 0
--*/
汪娜 计供科 女 团员 高级 本科
凌开明 技术科1 男 团员 中级 本科
周寅 质监科 男 团员 中级 本科
朱荷波 八车间 男 党员 初级 大专
邬静娜 八车间 女 党员 初级 本科
钱丹萍 八车间 女 党员 高级 本科
杜丽娟 三车间 女 党员 中级 本科
毛易耀 三车间 男 团员 中级 本科
王仲秋 四车间 男 党员 高级 本科报表如下:
性别 计供科 技术科1 质监科 八车间 三车间 四车间
男 0 1 1 1 1 1
女 1 0 0 2 1 0
党员 0 0 0 3 1 1
团员 1 1 1 0 1 0
高级 1 0 0 1 0 1
中级 0 1 1 0 2 0
初级 0 0 0 2 2 0
本科 1 1 1 2 2 1
大专 0 0 0 1 0 0
初中 0 0 0 0 0 0谢谢邹建,请指教!
set @s=''
select @s=@s+',['+workname+']=sum(case workname when '''+workname+''' then 1 else 0 end)'
from [table]
group by workname
exec('select 性别=sex'+@s+'
from(
select name,workname,sex from [table]
union all
select name,workname,zhenzhi from [table]
union all
select name,workname,zhichen from [table]
union all
select name,workname,xueli from [table]
)a group by sex')
go