1

This is my Table (invoice_payments):

invoice_payments table

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:

My Query Result

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

Thanks

1
  • 1
    I don't get the second select, why are you non just doing something like select invoice_id, sum(invoice_payments.amount) as total_paid, type from invoice_payments where invoice_payments.type!='Store' group by type, invoice_id ? Commented Oct 15, 2014 at 12:40

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

5 Comments

What about this query? How can I fix this query? select invoice_id, sum(invoice_payments.amount) as total_paid, sum(case when type='Store' then invoice_payments.amount else 0 end ) as total_balance, type from invoice_payments where invoice_payments.type!='Store' group by type, invoice_id
@Maria. in the above qry the total_balance always results 0.what is the need of it?
why will it be 0 always? I need total_paid and total_balance both
you are filtering by invoice_payments.type!='Store' , so it will fetch only the type other than store. And in the case statement you given as "when type='Store' then invoice_payments.amount" .
ok but I also need amount with type='store as a field, How can I acheive that?
1

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

1 Comment

What about this query? How can I fix this query? select invoice_id, sum(invoice_payments.amount) as total_paid, sum(case when type='Store' then invoice_payments.amount else 0 end ) as total_balance, type from invoice_payments where invoice_payments.type!='Store' group by type, invoice_id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.