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 query to get net profit stock wise

tid stock sid sval type
1 abc 1 100 buy
2 abc 2 120 buy
3 xyz 3 300 buy
4 abc 4 240 sell
5 xyz 5 250 sell

Query to get the following output

Output

stock profit/loss
abc 20
xyz -50

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

>Solution :

You can use a case expression to count "sell"s as profits and "buy"s as loses, and then sum them:

SELECT   stock, SUM(CASE type WHEN 'sell' THEN sval
                              WHEN 'buy'  THEN sval * -1
                    END) as "profit/loss"
FROM     stocks
GROUP BY stock
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