如何在结果集中将局部变量设置为特定值?

时间:2015-12-04 05:28:49

标签: sql sql-server variables

我有这个代码工作:

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 ;

我想将顶行的GameID保存为变量。

我试过这个,但似乎无法获得最多'购买'行的'游戏'的游戏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方式(INCORRECT SYNTAX NEAR 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;

2 个答案:

答案 0 :(得分:1)

我看到你正在选择两个元素(GameID和Title)。我想它只在寻找一个存储在局部变量中的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

答案 1 :(得分:0)

您可以使用ResultQuery将其存储到java中的本地变量,并使用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