CREATE FUNCTION [dbo].[API_CalcKnokRanks]
(
	@knokId int = null
)
RETURNS TABLE
AS
	RETURN (SELECT KnokId, Sum(r.Measure * f.Weight *f.Factor)/ Sum(f.Weight)*1000 RankValue from Signals 
	CROSS APPLY API_KnokRanks(Signals.KnokId) AS r
	LEFT JOIN RankFactors f on f.RankId=r.RankId and f.Code=r.Code
	where Signals.KnokId=ISNULL(@knokId, Signals.KnokId)
	Group by Signals.KnokId)


/*
SELECT  KnokId, r.*, f.* from Signals 
	CROSS APPLY API_KnokRanks(Signals.KnokId) AS r
	LEFT JOIN RankFactors f on f.RankId=r.RankId and f.Code=r.Code
SELECT SignalId KnokId, Sum(r.Measure * f.Weight *f.Factor)/ Sum(f.Weight) RankValue from Signals 
	CROSS APPLY API_KnokRanks(Signals.KnokId) AS r
	LEFT JOIN RankFactors f on f.RankId=r.RankId and f.Code=r.Code
	-- where Signals.KnokId=ISNULL(1, Signals.KnokId)
	Group by Signals.KnokId
	*/