SQL Server – How to Sum Values in Grouped Results

sql serversum

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

Best Answer

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.