我想基於一個CTE的值更新表中的數據..我有幾個問題,目前SQL Server說,它找不到列名稱WeightedRating,我真的不知道爲什麼..或什麼它在說什麼。如何從CTE中獲取的值進行更新? - SQL Server
目前我正在嘗試的是沿着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 ;;