日期:2014-05-18  浏览次数:20451 次

如何求变化列的平均值?
目前表结构:
bh,   xm,     cl1,wcl1,cl2,wcl2,cl3,   wcl3,   cl4,   wcl4.........
1     test       50     1.03       40       0.98     80       0.99       160     1.10
2     test2     25     0.51       80       1.96          

该表的字段是变化的,也就是说后面还可能有cl5,wcl5   等等字段,每个人(即每条记录的)也可能如test2那样,只有几个值,后面为null值。我现在想要产生一个字段,以显示wlc1,wcl2...所有以wcl开头的字段的平均值。
请教sql语句该怎么写?

------解决方案--------------------
--这回处理了遇到被零除错误。
create table tab(bh int, xm varchar(10),cl1 decimal(9,2),wcl1 decimal(9,2),cl2 decimal(9,2),wcl2 decimal(9,2),cl3 decimal(9,2), wcl3 decimal(9,2), cl4 decimal(9,2), wcl4 decimal(9,2))
insert tab
select 1 , 'test ' , 50 ,1.03 ,40 , 0.98 , 80 , 0.99 , 160 , 1.10
union select 2 , 'test2 ' ,25 ,0.51 ,80 , 1.96 ,null,null ,null ,null
union select 3 , 'test3 ' ,25 ,null ,80 , null ,null,null ,null ,null


declare @str varchar(8000),@str1 varchar(8000)
select @str= ' ' , @str1= ' '
select @str=@str+ '+isnull( '+name+ ',0) ',@str1=@str1+ '+( '+ 'select case when '+name+ ' is not null then 1 else 0 end from tab where bh=t.bh '+ ') ' from syscolumns where object_name(id)= 'tab ' and charindex( 'wcl ',name)> 0 group by name
set @str= 'select bh,[avg]=( '+stuff(@str,1,1, ' ')+ ')/case when ( '+stuff(@str1,1,1, ' ')+ ')=0 then 1 else ( '+stuff(@str1,1,1, ' ')+ ') end from tab t '

exec(@str)

drop table tab


/* 结果
(3 row(s) affected)

bh avg
----------- -------------------------
1 1.0250000000000
2 1.2350000000000
3 .0000000000000

*/