Function

CREATE FUNCTION GetTopRankAppByCategory
(@categoryname varchar(100))
RETURNS TABLE
AS
RETURN(
SELECT res1.CategoryID, cc.CategoryName, res1.AveCategoryScore FROM (SELECT res.CategoryID, SUM(res.TotalScore)/COUNT(res.AppID) AS AveCategoryScore 
FROM (SELECT app_score.AppID, app_score.TotalScore, app_cate.AppName, app_cate.CategoryID, app_cate.CategoryName FROM (SELECT ss.AppID, SUM(s.Score)/COUNT(s.ScoreID) AS TotalScore FROM SearchScore ss JOIN Score s ON ss.ScoreID = s.ScoreID
GROUP BY AppID) AS app_score INNER JOIN 
(SELECT res.AppID, res.AppName, c.CategoryID, c.CategoryName FROM (SELECT a.AppID, a.AppName, ad.CategoryID FROM App a INNER JOIN AppDetail ad ON a.AppID = ad.AppID) as res INNER JOIN Category c ON res.CategoryID = c.CategoryID) AS app_cate
ON app_score.AppID = app_cate.AppID) AS res
GROUP BY res.CategoryID) AS res1 
INNER JOIN Category cc ON cc.CategoryID = res1.CategoryID
WHERE cc.CategoryName = @categoryname
);

DROP FUNCTION GetTopRankAppByCategory

SELECT * FROM GetTopRankAppByCategory('TAX');

你可能感兴趣的:(Function)