给定的查询在sql中是否有效?

时间:2014-05-08 16:52:05

标签: mysql database

SELECT account_name ,SUM(debit)+SUM(credit) AS 'total_balance' 
AND SUM(total_balance) AS 'net_revenue'
FROM transaction

我想找到总余额和总余额的sum作为净收入,并且给我以下sql错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and sum(total_balance) as 'net_revenue' from transaction' at line 2

3 个答案:

答案 0 :(得分:0)

不,它不是有效的SQL。使用逗号分隔选择列表中的列。

SELECT account_name ,SUM(debit)+SUM(credit) AS 'total_balance',
  SUM(total_balance) AS 'net_revenue'
FROM transaction

apples, bananas and plums这样的列表的形成在自然英语中很常见,但在代码中却不常见。

答案 1 :(得分:0)

只需删除AND

SELECT 
    account_name,
    SUM(debit)+SUM(credit) AS 'total_balance',
    SUM(total_balance) AS 'net_revenue'
FROM transaction

注意:虽然上述查询在语法上有效,但SUM是一个组函数,您可能需要一些GROUP BY子句来选择account_name正确。像这样:

SELECT 
    account_name,
    SUM(debit)+SUM(credit) AS 'total_balance',
    SUM(total_balance) AS 'net_revenue'
FROM transaction
GROUP BY account_name

答案 2 :(得分:0)

这里有两件事:

  1. AND是一个布尔运算符。您需要使用逗号分隔多个列
  2. 您需要按帐户名称进行分组,才能按帐户名称获取计算值。
  3. 因此请将您的查询更改为:

    SELECT account_name, SUM(debit)+SUM(credit) AS 'total_balance', SUM(total_balance) AS 'net_revenue'
    FROM transaction
    GROUP BY account_name