我正在尝试根据 CTE 的值更新表中的数据..我有几个问题,目前 SQL Server 说它找不到列名 WeightedRating 我真的不知道为什么..或者它在说什么。
目前我正在尝试在 CTE 中混合 MERGE 关键字。
这是我的完整查询:
DECLARE @COUNT_VALUE FLOAT -- MINIMUM OF VOTES REQUIRED TO BE LISTED IN THE TOP
DECLARE @minimumVotesRequired FLOAT -- MINIMUM OF VOTES REQUIRED TO BE LISTED IN THE TOP
SET @minimumVotesRequired = 3
;WITH CTE_2 (SumOfVoteScore,CountOfVotes,IdProduct)
AS
(
SELECT
SUM(r.Stars) AS SumOfVoteScore, -- THIS IS THE SUMMATORY OF ALL THE STARS THAT WERE GIVEN TO THE PRODUCT
COUNT(rap.IdProduct) AS CountOfVotes, --HOW MANY RATINGS OF PRODUCTS WHERE MADE, this is the vote count
rap.IdProduct
FROM
glamstapp.Rating AS r INNER JOIN glamstapp.RatingAndProducts AS rap ON r.IdRating = rap.IdRating
GROUP BY
rap.IdProduct
)
,CTE_3 (idProduct,vote_count,vote_mean1,vote_mean2)
AS
(
SELECT CONVERT(FLOAT,rap.IdProduct) as IdProduct,
--ISNULL(CTE_2.SumOfVoteScore,0) AS vote_sum,
CONVERT(FLOAT,CTE_2.CountOfVotes) AS vote_count,
COALESCE((CONVERT(FLOAT,CTE_2.SumOfVoteScore)/ (CONVERT(FLOAT,CTE_2.CountOfVotes))),0) AS vote_mean1, --THE MEAN OF EACH PRODUCT
COALESCE((CONVERT(FLOAT,CTE_2.SumOfVoteScore)/ (CONVERT(FLOAT,CTE_2.CountOfVotes))),0) AS vote_mean2
FROM glamstapp.RatingAndProducts AS rap INNER JOIN CTE_2 ON rap.idProduct = CTE_2.idProduct
GROUP BY rap.IdProduct,
CTE_2.SumOfVoteScore,
CTE_2.CountOfVotes
)
MERGE INTO glamstapp.RatingAndProducts
USING
(
SELECT CTE_3.idProduct,(CONVERT(FLOAT,CTE_3.vote_count) / (CONVERT(FLOAT,CTE_3.vote_count) + @minimumVotesRequired))
* CONVERT(FLOAT,CTE_3.vote_mean1) +
(@minimumVotesRequired / (CONVERT(FLOAT,CTE_3.vote_count)+ @minimumVotesRequired))
* (SUM(CONVERT(FLOAT,CTE_3.vote_mean2))/(select count (CTE_3.vote_mean2) from CTE_3)) AS WeightedRating
FROM CTE_3
GROUP BY
CTE_3.vote_count,
CTE_3.IdProduct,
CTE_3.vote_mean1
)
AS Source
ON glamstapp.RatingAndProducts.idProduct = source.idProduct
WHEN MATCHED THEN
UPDATE SET glamstapp.RatingAndProducts.WeightedRating = //<--The error is present in here or so SQL Server points out when I double click on the error.
source.WeightedRating ;;