SQL:将两列相加为' Name'并在其中使用该名称

时间:2017-07-08 10:34:57

标签: mysql sql sum

MySQL的:

我试图在我的数据库中对两列进行求和并返回结果。我有点工作。

SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats GROUP BY Id

现在我总共有两个栏目,我希望能够使用' TotalMoney'在where子句?

SELECT Id, SUM(Money + Bank) AS TotalMoney FROM Players_Stats
WHERE TotalMoney BETWEEN 100000 AND 1000000
GROUP BY Id

我收到一条错误消息,说TotalMoney不存在,但我已经声明了。

2 个答案:

答案 0 :(得分:1)

SELECT Id, SUM(Money) + SUM(Bank) AS TotalMoney FROM Players_Stats 
GROUP BY Id HAVING SUM(Money) + SUM(Bank) BETWEEN 100000 AND 1000000

或:

SELECT ID,TotalMoney FROM 
(
SELECT Id, SUM(Money) + SUM(Bank) AS TotalMoney FROM Players_Stats 
    GROUP BY Id 
)Z WHERE Z.TotalMoney  BETWEEN 100000 AND 1000000

尝试以上查询。

答案 1 :(得分:1)

您想使用HAVING子句。它出现在GROUP BY之后。它可以使用表别名(在MySQL中):

SELECT Id, SUM(Money + Bank) AS TotalMoney
FROM Players_Stats
GROUP BY Id
HAVING TotalMoney BETWEEN 100000 AND 1000000;