Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL: sum rows with conditions

I have a table in the database as follows:

date       account      side     size     
2022-01-01 1            buy      50
2022-01-01 1            sell     25
2022-01-01 1            buy      35
2022-01-01 1            sell     10
2022-01-01 2            buy      100
2022-01-01 2            sell     50
2022-01-02 1            buy      10
2022-01-02 1            sell     10
2022-01-02 2            buy      100
2022-01-02 2            sell     10

What I want is to subtract the size when the side is ‘sell’ and add it when it is buy to have something like this:

date       account      volume
2022-01-01 1            50
2022-01-01 2            50
2022-01-02 1            0  
2022-01-02 2            90

I have tried the following

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select date, account, sum(case when size='sell' then size = -size else size = size end) as volume
group by date, account, side, size

But I get an error: ERROR: function sum(boolean) does not exist. HINT: No function matches the given name and argument types. You might need to add explicit type casts.

What am I doing wrong?

>Solution :

Conditional aggregation is the way to go here, but your logic is a bit off. Also, you want to aggregate by only the date and account.

SELECT date, account,
       SUM(CASE WHEN size = 'buy' THEN size ELSE -size END) AS volume
FROM yourTable
GROUP BY date, account
ORDER BY date, account;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading