简体   繁体   中英

SQL: getting sum of amounts of multiple rows in single table

This is my Table (invoice_payments):

发票付款表

I want to get rows grouped by invoice_id with sum of amount with specific condition. My SQL query:

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

I am getting this result:

我的查询结果

As you can see this is wrong. Please someone help/suggest a solution. I really appreciate any reply.

Thanks

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

Please post the expected output if the above query satisfy the needs.

You can use a case expression inside the sum function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM