I have 2 tables; Inbound & Outbound. Both of them have the same structure.
- TransactionId (int),
- Date (datetime),
- StoreItemId (int) [FK],
- Quantity (real)
I tried this select statement and the result as in the image below:
SELECT [StoreItemId], SUM([Quantity]) AS 'inbound' FROM [Inbound] GROUP BY [StoreItemId];
SELECT [StoreItemId], SUM([Quantity]) AS 'outbound' FROM [Outbound] GROUP BY [StoreItemId];
I tried a query:
SELECT
(SELECT SUM([Quantity]) AS 'inbound' FROM [Inbound] WHERE [Inbound].[StoreItemId] = 1) -
(SELECT SUM([Quantity]) AS 'Outbound' FROM [Outbound] WHERE [Outbound].[StoreItemId] = 1)
and the result was 105 (115-10 ; Inbound quantity for StoreItemId = 1 - Outbound quantity for StoreItemId = 1)
I tried combining both queries above to a query like this:
SELECT [StoreItemId] AS 'xyz'
(SELECT SUM([Quantity]) FROM [Inbound] WHERE [Inbound].[StoreItemId] = [xyz]) -
(SELECT SUM([Quantity]) FROM [Outbound] WHERE [Outbound].[StoreItemId] = [xyz])
FROM [StoreItem]
But it's just wrong
The result should be:
StoreItemId | Balance
----------------------
1 | 105
2 | 126
3 | 78
4 | 144
5 | 100
6 | 179