I am trying to set a User function to get alphas, Betas and R2 from a linear regression within sql.
I can get the data through the select statement, but it fails to register as a Function, stating
"Select statements included within a function cannot return data to a client."
I have tried to Set the result of the select statement into the @Beta vaiable but that too doesnt work.
Create Function MasterDB.Uf_AlphaBetaR2(@X int,@Y int)
RETURNS float
AS
Begin;
DECLARE @Beta float;
WITH
some_table( x, y) AS
(
SELECT Performance_1.[Return] AS x, Performance_2.[Return] AS y
FROM dbo.Performance INNER JOIN
dbo.Performance AS Performance_2 ON dbo.Performance.Date = Performance_2.Date INNER JOIN
dbo.Performance AS Performance_1 ON dbo.Performance.Date = Performance_1.Date
WHERE (dbo.Performance.ID = 70305 OR
dbo.Performance.ID = @X) AND (dbo.Performance.[Return] IS NOT NULL) AND (Performance_1.ID = @Y) AND (Performance_2.ID = @X)
),
average_estimate AS
( SELECT avg(x) as xbar
,avg(y) as ybar
FROM some_table
),
beta_estimate AS
( SELECT CASE COALESCE(SUM((x-xbar)*(x-xbar)),0)
WHEN 0 THEN NULL
ELSE SUM((x-xbar)*(y-ybar)) / SUM((x-xbar)*(x-xbar))
END AS Beta
FROM some_table pd
Cross JOIN average_estimate pa
),
alpha_estimate AS
( SELECT ybar - xbar * pb.Beta AS Alpha
FROM beta_estimate pb
Cross JOIN average_estimate pa
),
sumsquares_estimate AS
( SELECT SUM((y-ybar)*(y-ybar)) AS SS_tot
,SUM((y-(Alpha+Beta*x)) * (y-(Alpha+Beta*x))) AS SS_err
FROM alpha_estimate pa
cross JOIN beta_estimate pb
Cross JOIN some_table
Cross JOIN average_estimate ae
)
SELECT Beta
FROM alpha_estimate pa
Cross JOIN beta_estimate pb
Cross JOIN sumsquares_estimate ss ;
RETURN @Beta;
END;