Mysql SQL:获取单个表中多行的金额之和
这是我的表格(发票和付款): 我想按Mysql SQL:获取单个表中多行的金额之和,mysql,sql,Mysql,Sql,这是我的表格(发票和付款): 我想按invoice\u id和特定条件下的金额之和对行进行分组。 我的SQL查询: select invoice_id, (select sum(invoice_payments.amount) from invoice_payments where invoice_payments.type!='Store') as total_paid, type from invoice_payments where invoice_payments.type!='S
invoice\u id
和特定条件下的金额之和对行进行分组。
我的SQL查询:
select invoice_id, (select sum(invoice_payments.amount) from invoice_payments where
invoice_payments.type!='Store') as total_paid, type from invoice_payments where
invoice_payments.type!='Store' group by invoice_id
我得到的结果是:
正如你所看到的,这是错误的。请有人帮忙/提出解决方案。我真的很感谢你的回复
谢谢
如果上述查询满足需要,请发布预期输出。您可以在
sum
函数中使用case
表达式:
SELECT invoice_id,
SUM(CASE WHEN type != 'Store' THEN amount ELSE 0 END) AS total_paid
FROM invoice_payments
GORUP BY invoice_id
我没有得到第二个选择,为什么你不只是做一些像
select invoice\u id,sum(invoice\u payments.amount)作为total\u payment,输入from invoice\u payments where invoice\u payments.type!='Store“按类型分组,发票id
?此查询如何?如何修复此查询<代码>选择发票id,金额(发票付款.金额)作为总付款,金额(当类型为'Store'时,则为发票付款.金额0结束)作为总余额,从发票付款中键入,其中发票付款.键入!='按类型、发票编号分组的门店@Maria。在上述qry中,总余额始终为0。它需要什么?为什么总是为0?我需要您按发票付款筛选的已付款总额和余额总额。键入!='Store',因此它将只获取除Store之外的类型。在您给出的case语句中是“when type='Store'然后invoice\u payments.amount”。好的,但我还需要使用type='Store作为字段的amount,我如何实现它?这个查询呢?如何修复此查询<代码>选择发票id,金额(发票付款.金额)作为总付款,金额(当类型为'Store'时,则为发票付款.金额0结束)作为总余额,从发票付款中键入,其中发票付款.键入!='门店“按类型、发票编号分组”
SELECT invoice_id,
SUM(CASE WHEN type != 'Store' THEN amount ELSE 0 END) AS total_paid
FROM invoice_payments
GORUP BY invoice_id