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
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;