SQL server一元线性回归统计分析

2014-11-24 12:15:17 · 作者: · 浏览: 1
SQL server一元线性回归统计分析
备注 简单的一元线性数学方程 y=ax+b 其中 a为斜率,b 为截距。
a=协方差/x方差 www.2cto.com
b=y(平均数) -a*x(平均数)
1.首先电子表格数据
www.2cto.com
关健点,2008-02,2008-03,2008-04, 需要转成x, 需要2008-02 变成 1,2008-03 变成2 .......................这样需要用到window function 函数。
ok,下面简单代码,稍作修改可以封装成存储过程。
[sql]
with T as
(
select '2008-02' as year,45 as salary
union all
select '2008-03',55
union all
select '2008-04',66
union all
select '2008-05',77
)
select rank() OVER(ORDER BY year) AS x,YEAR,salary as y
into #one
from T
declare @u_x decimal(8, 2) --x的平均值
declare @u_y decimal(8, 2) --y的平均值
declare @s2_x decimal(8, 2)--X方差
declare @cov_x_y decimal(8, 2) --协方差
--############### 求平均值 ############
select @u_x= avg(x*1.0),@u_y=avg(y*1.0)
from #one
--############### 求平均值 ############
--############### 协方差,X方差 ############
select @cov_x_y=sum((x-@u_x)*(y-@u_y))/(select count(1) from #one),
@s2_x=sum (power((x-@u_x),2))
from #one
--############### 协方差,X方差 ############
declare @a decimal(8, 2),@b decimal(8,2)
set @a=@cov_x_y/@s2_x
set @b=@u_y-@a*@u_x
print 'y=a*x+b'
print 'y='+cast(@a as varchar(max))+'*x + '+cast(@b as varchar(max))

结果是
y=a*x+b
y=10.70*x + 34.00
OK一元函数回归函数建立了
其中里面有一条蓝色的线,已被红色的线 复盖了。
这里可能是自己用的测试数据还比较符合线性,看上去还顺眼。
更正 求转成X 
[sql]
with T as
(
select '2008-02' as year,45 as salary
union all
select '2008-03',55
union all
select '2008-04',66
union all
select '2008-05',77
)
select rank() OVER(ORDER BY year) AS x,YEAR,salary as y
from
(select *
from T
union all
select '2008-06' as year,null as y) as ct
来源 http://blog.csdn.net/zengxinwen/article/details/8648711