SQL:获取单个表中多行的总和

时间:2014-10-15 12:35:02

标签: mysql sql

这是我的表(invoice_payments):

invoice_payments table

我希望获得按invoice_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

我得到了这个结果:

My Query Result

你可以看到这是错误的。请有人帮忙/建议解决方案。我真的很感激任何回复。

由于

2 个答案:

答案 0 :(得分:1)

select  invoice_id,  sum(invoice_payments.amount)  
from    invoice_payments 
where   invoice_payments.type!='Store'
group   by invoice_id.

如果上述查询满足需要,请发布预期输出。

答案 1 :(得分:1)

您可以在case函数中使用sum表达式:

SELECT   invoice_id,
         SUM(CASE WHEN type != 'Store' THEN amount ELSE 0 END) AS total_paid
FROM     invoice_payments
GORUP BY invoice_id