当前位置: 代码迷 >> Sql Server >> 读取字段求平均值解决方案
  详细解决方案

读取字段求平均值解决方案

热度:42   发布时间:2016-04-24 11:02:47.0
读取字段求平均值

SQL语句怎样读取上面表的第五个字段,求平均值,然后存到一个新表中!最好用存储过程实现!
------解决方案--------------------
---创建模拟数据
create table bigstr(
id int identity(1,1) not null,
usefuldata nvarchar(max)
)
insert into bigstr(usefuldata) values('2245.9 2246.0 2246.1 2246.2 2246.3 2246.4 2246.5 2246.6 2246.7 2246.8 2246.9 2247.0 2247.1 2247.2 2247.3 2247.4 2247.5 2247.6 2247.7 2247.8 2247.9 2248.0 2248.1 2248.2 2248.3 2248.4 2248.5 2248.6 2248.7 2248.8 2248.9 2249.0 2249.1 2249.2 2249.3 2249.4 2249.5 2249.6 2249.7 2249.8 2249.9 2250.0 2250.1 2250.2 2250.3 2250.4 2250.5 2250.6 2250.7 2250.8 2250.9 2251.0 2251.1 2251.2 2251.3 2251.4 2251.5 2251.6 2251.7 2251.8 2251.9 2252.0 2252.1 2252.2 2252.3 2252.4 2252.5 2252.6 2252.7 2252.8 2252.9 2253.0 2253.1 2253.2 2253.3 2253.4 2253.5 2253.6 2253.7 2253.8 2253.9 2254.0 2254.1 2254.2 2254.3 2254.4 2254.5 2254.6 2254.7 2254.8 2254.9 2255.0 2255.1 2255.2 2255.3 2255.4 2255.5 2255.6 2255.7 2255.8 2255.9 2256.0 2256.1 2256.2 2256.3 2256.4 2256.5 2256.6 2256.7 2256.8 2256.9 2257.0 2257.1 2257.2 2257.3 2257.4 2257.5 2257.6 2257.7 2257.8 2257.9 2258.0 2258.1 2258.2 2258.3 2258.4 2258.5 2258.6 2258.7 2258.8 2258.9 2259.0 2259.1 2259.2 2259.3 2259.4 2259.5 2259.6 2259.7 2259.8 2259.9 2260.0 2260.1 2260.2 2260.3 2260.4 2260.5 2260.6 2260.7 2260.8 2260.9 2261.0 2261.1 2261.2 2261.3 2261.4 2261.5 2261.6 2261.7 2261.8 2261.9 2262.0 2262.1 2262.2 2262.3 2262.4 2262.5 2262.6 2262.7 2262.8 2262.9 2263.0 2263.1 2263.2 2263.3 2263.4 2263.5 2263.6 2263.7 2263.8 2263.9 2264.0 2264.1 2264.2 2264.3 2264.4 2264.5 2264.6 2264.7 2264.8 2264.9 2265.0 2265.1 2265.2 2265.3 2265.4 2265.5 2265.6 2265.7 2265.8')
select usefuldata from bigstr

go

---创建存储过程求平均值
create proc [dbo].[proc_bigavg](@c  nvarchar(max),@split varchar(2),@v float output)
   
as
  declare @t table(col float) 
   begin 
      while(charindex(@split,@c)<>0) 
        begin 
          insert @t(col) values (substring(@c,1,charindex(@split,@c)-1)) 
          set @c = stuff(@c,1,charindex(@split,@c),'') 
        end 
      insert @t(col) values (convert(float ,convert (nvarchar,@c))) 
       select @v=AVG(col) from @t
    end 
    
---演示存储过程求平均值
 declare @splittemp varchar(2)
 declare @ctemp  nvarchar(max)
 declare @vtemp float
 set @splittemp=' ';
 select @ctemp=usefuldata from bigstr
 
 exec [proc_bigavg] @ctemp,@splittemp,@vtemp output
 print @vtemp
 
 

 

 


 

  相关解决方案