2015-12-04 57 views
0

我有這樣的代碼工作:如何在結果集中將局部變量設置爲特定值?

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; 

回答

1

我看到你選擇兩個元素(遊戲ID和標題)。我想它只是尋找一個GameID來存儲在本地變量中。這是在沒有樣本數據的情況下在黑暗中拍攝的全部照片,但試試這個或使用它來到你需要的位置。

DECLARE @BestSellerID int; 

with cte 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 
) 
set @BestSellerID = select top 1 cte.GameID from cte 

select @BestSellerID 
+0

語法錯誤附近「頂」但是,如果改變代碼不分配:從cte中選擇top 1 cte.GameID;我得到正確的GameID!但它不會讓我分配變量 – MrPickles7

+0

試試這個:set @BestSellerID =從cte中選擇top 1 cte.GameID。我還對原始答案做了一些更改,您也會希望包括這一點。 – tshoemake

+0

在DESC和設置var之後,仍然從分號中得到語法錯誤,cte表達式有不同的語法嗎? – MrPickles7

0

您可以在Java中使用ResultQuery序存儲到一個局部變量與MySQL數據庫

我的代碼的建議是:

ResultSet rs=st.executeQuery("SELECT TOP 1 COUNT(*) AS NumSold, Game.Title,Game.GameID 
    FROM Game JOIN Purchase ON Game.GameID = Purchase.GameID 
    GROUP BY Game.Title 
    ORDER BY NumSold DESC ;"); 
    if(rs.next()) 
    int GameID=rs.getInt("Game.GameID"); 

//You can use a array if you want to store large set of numbers 
+1

謝謝,但我被困在SQL服務器內 – MrPickles7

相關問題