从SQL查询中的两列中减去值

时间:2018-07-31 10:00:08

标签: sql sql-server

有两列,我想减去它们。我正在尝试对[付款]列求和,然后从[total_bill]列中减去它。下面是我的代码,它给了我一个错误,它无法对包含聚合或子查询的表达式执行聚合函数。

SELECT SUM((bill_record.total_bill)-SUM(invoice_payments.payment)) AS [LEFT AMOUNT] 

5 个答案:

答案 0 :(得分:1)

您需要使用分组方式,但是您可能只想对付款进行总计,然后从单个总账单中减去付款。

SELECT bill_record.total_bill - SUM(invoice_payments.payment) AS [LEFT AMOUNT] 
FROM bill_record INNER JOIN invoice_payments ON bill_record.PKColumn = invoice_payments.FKColumn 
WHERE bill_record.PKColumn = @billId
GROUP BY bill_record.total_bill

请注意,此处的group by起作用,因为您也在WHERE子句中进行过滤。如果要获取多个账单的结果,还可以按唯一的账单标识符分组,并将其返回到SELECT中。

SELECT bill_record.PKColumn AS BillId, bill_record.total_bill - SUM(invoice_payments.payment) AS [LEFT AMOUNT] 
FROM bill_record INNER JOIN invoice_payments ON bill_record.PKColumn = invoice_payments.FKColumn 
GROUP BY bill_record.PKColumn, bill_record.total_bill

答案 1 :(得分:0)

您似乎想要一个sum而不是两个:

SELECT SUM(bill_record.total_bill - invoice_payments.payment) AS [LEFT AMOUNT]
FROM . . .

答案 2 :(得分:0)

在您的请求中,从...中选择项目。 该请求应类似于

SELECT SUM((bill_record.total_bill)-SUM(invoice_payments.payment)) AS [LEFT AMOUNT] FROM YOUR TABLE NAME

答案 3 :(得分:0)

db.CreateCollection("users")

答案 4 :(得分:0)

在使用SUM聚合函数时,必须正确使用group by子句

和选择列数必须在group by子句上

SELECT SUM((bill_record.total_bill)-SUM(invoice_payments.payment)) AS [LEFT AMOUNT] 

错误的出处可以在列的子句编号中进行分组,否则查询将起作用