﻿CREATE FUNCTION [dbo].[API_CalcKnokserRanks]
(
	@userId int = null
)
RETURNS TABLE
AS
	RETURN (SELECT UserId, Sum(r.Measure * f.Weight *f.Factor)/ Sum(f.Weight) * 1000 RankValue from Users
	CROSS APPLY API_KnokserRanks(Users.UserId) AS r
	LEFT JOIN RankFactors f on f.RankId=r.RankId and f.Code=r.Code
	where Users.UserId=ISNULL(@userId, Users.UserId)
	Group by Users.UserId)

/*
SELECT UserId UserId, r.*, f.* from Users
	CROSS APPLY API_KnokserRanks(Users.UserId) AS r
	LEFT JOIN RankFactors f on f.RankId=r.RankId and f.Code=r.Code
SELECT UserId UserId, Sum(r.Measure * f.Weight *f.Factor)/ Sum(f.Weight) RankValue from Users 
	CROSS APPLY API_KnokserRanks(Users.UserId) AS r
	LEFT JOIN RankFactors f on f.RankId=r.RankId and f.Code=r.Code
	Group by Users.UserId
*/
