I have a table with multiple value columns. values can be an integer or NULL. example:
LFNR WertA WertB WertC
1 1 1 2
2 100 100 200
3 NULL 1 NULL
5 1 NULL 1
6 0 0 0
40 NULL 1 NULL
I need to get the average of lets say top 3 values beeing not NULL for each column. For a single column I get the desired average with this statement:
SELECT AVG(WertA) FROM (SELECT TOP 3 WertA FROM synta_rollmw WHERE WERTA IS NOT NULL ORDER BY lfnr DESC)u
To use this value in a SSRS, my idea was to use a function like this:
SELECT dbo.func_avg_Wert(WertA), dbo.func_avg_Wert(WertB), ...
Here is my code for the function:
CREATE FUNCTION dbo.func_avg_Wert (@col_in varchar(15))
RETURNS int
AS
BEGIN
DECLARE @rollmw int
DECLARE @sqlquery VARCHAR(1000)
SET @sqlquery = ('SELECT AVG(@col_in) FROM (SELECT TOP 3 @col_in FROM synta_rollMW WHERE @col_in IS NOT NULL ORDER BY lfnr DESC)u')
EXEC @sqlquery
RETURN @rollmw
END
GO
But if I try to use the function, I get "Column name 'WertA' not valid. What is wrong or is there a better way ? Thanks