I am getting 2 rows(9500) for 111 in the result, could you please advise on the right approach, I need like, Balance = (sum of bought – sum of sold)
x
#Table T1#
+---------+--------+------+------+
| ACCOUNT | TRANS | AMT | YEAR |
+---------+--------+------+------+
| 111 | BOUGHT | 8000 | 2019 |
| 111 | BOUGHT | 2000 | 2019 |
| 111 | SOLD | 500 | 2019 |
| 222 | BOUGHT | 6000 | 2018 |
| 222 | SOLD | 300 | 2018 |
+---------+--------+------+------+
Query
SELECT (A.BOUGHTs - B.SOLDs) AS BALANCE
FROM T1
INNER JOIN
(SELECT SUM(AMT) AS BOUGHTs
FROM T1
WHERE TRANS = 'BOUGHT'
) A
ON T1.ACCOUNT = A.ACCOUNT
INNER JOIN
(SELECT SUM(AMT) AS SOLDs
FROM T2
WHERE TRANS = 'SOLD'
) B
ON T1.ACCOUNT = B.ACCOUNT
WHERE T1.ACCOUNT = 111
AND T1.YEAR = 2019
Advertisement
Answer
You can use conditional aggregation:
select account, year,
sum(case when trans = 'bought' then amt
when trans = 'sold' then - amt
else 0
end) as diff
from t
group by account, year;
If you want this for only one account, you can add a where
clause:
select account, year,
sum(case when trans = 'bought' then amt
when trans = 'sold' then - amt
else 0
end) as diff
from t
where account = 111 and year = 2019
group by account, year;