A
A
Alexander Seleznev2021-10-16 10:33:37
SQL Server
Alexander Seleznev, 2021-10-16 10:33:37

How to find the difference of sums by condition?

How to find the difference of sums by condition? More details: there are two columns in one type of document, in the second its sum and you need to subtract the first sum of documents by type (Data grouped) from the second. Example:

select (sum(amount) and idoperation = 1) - (sum(amount) and idoperation = 2)
from journal group by idoperation
But executing such a query reports a syntax error.
If it is simpler, then subtract the value of the subsequent ones from the first value616a9f1a75ed4597970787.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-10-16
@rozhnev

Everything can be easier:

SELECT 
SUM(ammount * (CASE WHEN idoperation = 1 THEN 1 ELSE -1 END)) AS result
FROM journal
;

SQL SUM fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question