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

Add Infamous Condition to SQL Query

I have this simple table named Transaction_Body

ID ItemsID DateX ItemAmount totalcost
1 1 2023-06-08 -1 -500
2 1 2023-06-07 -2 -1000
3 1 2023-06-07 1 400
4 1 2023-06-03 2 800

Please notice that I have some values < 0

I have this simple query here

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 
    SUM(T.totalcost) / SUM(T.ItemAmount) as AVG
FROM Transaction_Body T
Where T.ItemsID = 1 and T.DateX <='2023-06-07' 
group by T.ItemsID

This code gives me the average but I want to add a condition beside these conditions up

(( If ‘ItemsAmount’ < 0 in ‘DateX’ = ‘2023-06-07’ Just ignore it from calculation ))

>Solution :

Try the below query: –

SELECT 
    SUM(CASE WHEN T.ItemAmount < 0 AND T.DateX = '2023-06-07' THEN 0 ELSE T.totalcost END) /
    SUM(CASE WHEN T.ItemAmount < 0 AND T.DateX = '2023-06-07' THEN 0 ELSE T.ItemAmount END) AS AVG
FROM Transaction_Body T
WHERE T.ItemsID = 1 AND T.DateX <= '2023-06-07'
GROUP BY T.ItemsID;
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