Are there any Linear Regression Function in SQL Server?

前端 未结 8 1588
遇见更好的自我
遇见更好的自我 2020-12-12 17:19

Are there any Linear Regression Function in SQL Server 2005/2008, similar to the the Linear Regression functions in Oracle ?

8条回答
  •  独厮守ぢ
    2020-12-12 17:52

    Here it is as a function that takes a table type of type: table (Y float, X double) which is called XYDoubleType and assumes our linear function is of the form AX + B. It returns A and B a Table column just in case you want to have it in a join or something

    CREATE FUNCTION FN_GetABForData(
     @XYData as XYDoubleType READONLY
     ) RETURNS  @ABData TABLE(
                A  FLOAT,
                B FLOAT, 
                Rsquare FLOAT )
     AS
     BEGIN
        DECLARE @sx FLOAT, @sy FLOAT
        DECLARE @sxx FLOAT,@syy FLOAT, @sxy FLOAT,@sxsy FLOAT, @sxsx FLOAT, @sysy FLOAT
        DECLARE @n FLOAT, @A FLOAT, @B FLOAT, @Rsq FLOAT
    
        SELECT @sx =SUM(D.X) ,@sy =SUM(D.Y), @sxx=SUM(D.X*D.X),@syy=SUM(D.Y*D.Y),
            @sxy =SUM(D.X*D.Y),@n =COUNT(*)
        From @XYData D
        SET @sxsx =@sx*@sx
        SET @sxsy =@sx*@sy
        SET @sysy = @sy*@sy
    
        SET @A = (@n*@sxy -@sxsy)/(@n*@sxx -@sxsx)
        SET @B = @sy/@n  - @A*@sx/@n
        SET @Rsq = POWER((@n*@sxy -@sxsy),2)/((@n*@sxx-@sxsx)*(@n*@syy -@sysy))
    
        INSERT INTO @ABData (A,B,Rsquare) VALUES(@A,@B,@Rsq)
    
        RETURN 
     END
    

提交回复
热议问题