我有這樣的代碼工作:如何在結果集中將局部變量設置爲特定值?
SELECT TOP 1 COUNT(*) AS NumSold, Game.Title
FROM Game JOIN Purchase ON Game.GameID = Purchase.GameID
GROUP BY Game.Title
ORDER BY NumSold DESC ;
我想排在前列的遊戲ID保存到一個變量。
我已經試過了,但似乎無法得到「遊戲」最「購買」行的遊戲ID。當我將變量轉換爲絕望時,我可以獲得各種遊戲的購買行數。
SET @BestSellerID = (SELECT TOP 1 COUNT(Game.GameID) AS Best
FROM Game JOIN Purchase ON Game.GameID = Purchase.GameID
ORDER BY Best DESC
);
我曾嘗試SELECT太(附近有語法錯誤TOP):
DECLARE @BestSellerID int;
SELECT @BestSellerID = TOP 1 COUNT(Game.GameID) AS NumSold, Game.Title
FROM Game JOIN Purchase ON Game.GameID = Purchase.GameID
GROUP BY Game.Title
ORDER BY NumSold DESC ;
這是不可能的,因爲沒有辦法讓標結果呢?有人可以向我解釋如何從結果集中獲取變量嗎?是否有一些我錯過的概念,是否有一種特殊的方式可以在查詢完成後與他們交談?謝謝。
與用戶tshoemake的幫助下確定和語法摸索這個固定我的問題:
DECLARE @BestSellerID int;
with cte_bs as
(
SELECT TOP 1 COUNT(Game.GameID) AS NumSold, Game.GameID
FROM Game JOIN Purchase ON Game.GameID = Purchase.GameID
GROUP BY Game.GameID
ORDER BY NumSold DESC
)
select @BestSellerID = (SELECT cte_bs.GameID FROM cte_bs)
select @BestSellerID AS BestSellerGameID;
語法錯誤附近「頂」但是,如果改變代碼不分配:從cte中選擇top 1 cte.GameID;我得到正確的GameID!但它不會讓我分配變量 – MrPickles7
試試這個:set @BestSellerID =從cte中選擇top 1 cte.GameID。我還對原始答案做了一些更改,您也會希望包括這一點。 – tshoemake
在DESC和設置var之後,仍然從分號中得到語法錯誤,cte表達式有不同的語法嗎? – MrPickles7