'Subtract values from same table and two different columns
This is my table with data:
Table input_data:
+-------------+------------+-------------+-------------+
| UID | Code | QTOut | QTIn |
+-------------+------------+-------------+-------------+
| A | 1 | 5000 | 0 |
| A | 2 | 20000 | 0 |
| A | 3 | 22000 | 0 |
| A | 4 | 14000 | 0 |
| A | 1 | 0 | 5000 |
| A | 2 | 0 | 4000 |
| A | 4 | 0 | 11 |
| A | 1 | 1000 | 0 |
+-------------+------------+-------------+-------------+
And this should be the output:
Table output_data:
+-------------+------------+-------------+
| UID | Code | Total |
+-------------+------------+-------------+
| A | 1 | 1000 |
| A | 2 | 16000 |
| A | 4 | 22000 |
| A | 3 | 13899 |
+-------------+------------+-------------+
The goal is for each Code to get how much pieces left.
So far I tried on this way but result is 0:
SELECT o.UID, o.Code, (o.QTOut- tt.QTIn) AS Total
FROM input_data o
LEFT JOIN input_data tt
ON o.UID = tt.UID
WHERE o.UID= 'A'
GROUP BY o.Code
Solution 1:[1]
SELECT uid,
code,
Sum(qtout) - Sum(qtin) AS Total
FROM input_data
GROUP BY uid,
code
Solution 2:[2]
Your code was very close. You just needed to aggregate your result using the SUM function.
The WHERE limits your result to the requested [UID].
SELECT o.UID,
o.CODE,
SUM(QTOut) - SUM(QTIn) AS Total
FROM input_data o
WHERE o.UID = 'A'
GROUP BY UID,
CODE
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RF1991 |
| Solution 2 | cruzan |
