针对不确定列做一个查询报表的做法..
不知道我能不能表达清楚...
情况如下..
有这样两张表:tab1----------------jldm | jlmc---------------- 1 交路A 2 交路B----------------tab2-------------------------name | jldm | xtrq张三 1 9.15李四 2 9.15张三 2 9.16--------------------------最后需要展示的结果是-----------------------------------姓名 | 交路A | 交路B 张三 1 1李四 0 1------------------------------------
--生成测试表和数据create table tab1( jldm int,jlmc varchar(10))create table tab2( name varchar(10), jldm int,xtrq varchar(10))truncate table tab1truncate table tab2insert into tab1(jldm,jlmc) values(1,'交路A')insert into tab1(jldm,jlmc) values(2,'交路B')insert into tab1(jldm,jlmc) values(3,'交路C')insert into tab1(jldm,jlmc) values(4,'交路D')insert into tab2(name,jldm,xtrq) values('张三',1,'9.15')insert into tab2(name,jldm,xtrq) values('李四',2,'9.15')insert into tab2(name,jldm,xtrq) values('张三',2,'9.15')insert into tab2(name,jldm,xtrq) values('王五',1,'9.15')insert into tab2(name,jldm,xtrq) values('王五',2,'9.15')insert into tab2(name,jldm,xtrq) values('王五',3,'9.15')insert into tab2(name,jldm,xtrq) values('王五',4,'9.15')drop table #lsselect a.jldm,a.name,a.xtrq,b.jlmc into #ls from tab2 a,tab1 b where a.jldm=b.jldm --关键sql语句declare @s nvarchar(4000),@sql varchar(8000)set @s='set @s=''''select @s=@s+'',[''+cast(rtrim([jlmc]) as varchar)+'']=sum(case [jlmc] when ''''''+cast([jlmc] as varchar)+'''''' then 1 else 0 end)''from [#ls]group by [jlmc]'print @sexec sp_executesql @s,N'@s varchar(8000) out',@sql outprint @sqlexec('select name'+@sql+' from #ls group by [name]' )