How do I calculate these two aliases and show them in other columns?
SELECT SUM(qty1) AS ali_qty1,
(SELECT SUM(qty2) FROM table2 WHERE col2 = 'B') AS ali_qty2,
(SELECT SUM(ali_qty1) - SUM(ali_qty2) as total_qty)
FROM table1
WHERE col1= 'A'
table1
ID | col1 | qty1
------------------
1 | A | 50
2 | A | 20
table2
ID | col2 | qty2
------------------
1 | B | 50
2 | B | 10
expected output
ID | ali_qty1 | ali_qty2 | ali_qty3
-------------------------------------
1 | 70 | 60 | 10
2
Answers
For this data, we could just cross join two aggregate queries, then perform the computation:
Note that this always returns one row – however any of the two sums may be
null
, in which case you might want to usecoalesce()
in the subtraction.