0

So i need to sum the value "amount" where where debit_id and transfer_id are equals: Table Example:

debit_id | transfer_id | amount | debit_type

1184685 | 861288 | 25.5 | 2

1184685 | 861288 | 59.5 | 2

1168516 | 861288 | 23 | 0

Right now i use this query thaht gives me almost the expected values

    WITH ct AS
  ( SELECT *,rn = ROW_NUMBER() OVER (PARTITION BY debit_id, transfer_id
   ORDER BY id DESC)
    FROM transfer_debits
  )
SELECT debit_id, transfer_id, amount, debit_type
FROM ct
WHERE rn = 1 AND transfer_id = 861288
ORDER BY debit_id, transfer_id;

I need this result but with the sum of the field amount grouped by debit_id and transfer_id Desired result should be:

debit_id | transfer_id | amount | debit_type

1184685 | 861288 | 85 | 2

1168516 | 861288 | 23 | 0

1 Answer 1

0

Try something like this:

Select debit_id, transfer_id, sum(amount) as "Amount_Sum"
from Transfer_debits
where transfer_id = 861288
group by  debit_id, transfer_id

For the debit_type, if you want a different sum depending on its value, just add it to the select and the group by.

3
  • Is there a way to use this query but adding another column in the select statement without adding it to the Group By Clause Apr 14, 2020 at 17:07
  • sure, but you'll need to have it in a "max", "min", "sum" etc, function as it will not be group by this row. (let's say your agregation by debit_id and Tranfer_id returns 2 different debit_type... SQL cannot show both values in the same line) Apr 14, 2020 at 17:10
  • 1
    Okay i already tried it and it does what i need, thank you very much sir Apr 14, 2020 at 17:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.