有些答案
http://topic.csdn.net/u/20100603/10/18f98fa7-66a3-444c-8e3c-651d0eeb79f3.html?seed=285216885&r=65965704#r_65965704用个场景描述下:
有一份问卷,其中有两道题目,拿男女球类做例子
题目A有两两个选项 男 女 对应A表
题目B有3个选项 足球 篮球 排球 对应B表
答案 对应C表现在运算结果就是想做一个交叉统计,所有男的选了某个球类占总人数的百分比,所有女的选了某个球类占总人数的百分比,总计最后横竖加起来都应该是100%表 A
Choice_Row_ID Choice_Name
1 足球
2 篮球
3 排球
表 B
Choice_Row_ID Choice_Name
4 男   
5 女表 C
Answer_ID Choice_Row_ID
1 1
1 4
2 2
2 5   结果
       男(计数)   N%     女(计数) N%    总计数    N%
足球 1  50%  0  0.0%  1  50%
篮球 0  0.0%  1  50%  1  50%
排球 0  0.0%    0  0.0%  0  0.0%
总计 1  50%  1  50%  2  100%

解决方案 »

  1.   

    declare @sql varchar(8000),@sql1 varchar(8000)
    set @sql = ''
    select @sql = @sql + ' , sum(case when t.bname = ''' + Choice_Name + ''' then 1  else 0 end) [' + Choice_Name + '],
    ltrim(sum(case when bname='''+Choice_Name+''' then 1 else 0 end )*100/(select count( distinct Answer_ID) from tc))+''%'' as [百分比]'
    from (select distinct Choice_Name from tb) as a
    set @sql = @sql + ',
    sum( case when Answer_ID is null then 0 else 1 end ) [总计数],
    ltrim(sum( case when Answer_ID is null then 0 else 1 end )*100/(select count(distinct Answer_ID) from tc))+''%'' as [百分比] from (select Answer_ID,max(a.Choice_Row_ID) aid,max(isnull(a.Choice_Name,''unknown'')) aname,max(b.Choice_Row_ID) bid,max(b.Choice_Name) bname 
    from ta a --哪个表数据在前哪个就是在这里ta
    full join (select rn=row_number()over(partition by Answer_ID order by getdate()) ,* from tc) c on c.rn=1 and c.Choice_Row_ID=a.Choice_Row_ID 
    left join tb b --哪个表数据在前哪个就是在这里tb  on c.rn=2 and c.Choice_Row_ID=b.Choice_Row_ID 
    group by Answer_ID) t '
    exec('select aname  as A'+ @sql+' where aname <> ''unknown'' group by aname union all '+'select ''总计'''+@sql+'')
      

  2.   

    请参考:create table tb(名称 varchar(10),数量  numeric(10),类型 varchar(5))
    Insert into tb 
    select 'L001','1','A'
    union all select 'L001','2','B'
    union all select 'L002','5','C'
    union all select 'L003','6','D'
    union all select 'L004','9','A'
    union all select 'L004','5','D'select * from tbdeclare @sql varchar(1000)
    set @sql=''
    select @sql=@sql+',['+max(类型)+']=sum(case 类型 when '''+max(类型)+''' then 数量 else 0 end)'
    from tb group by 类型 
    print @sqlexec('select 名称'+@sql+' from  tb  group by 名称')
    --结果
    名称      A       B        C        D
    ---------------------------------------
    L001 1 2 0 0
    L002 0 0 5 0
    L003 0 0 0 6
    L004 9 0 0 5