A) When goods are sold, a table will record an “O” in column ID & a “N” in column TYPE:-
SKU ID TYPE NR
-------------------------
HAB1122 O N 201211
B) When goods are returned, a table will record an “O” in column ID & a “R” in column TYPE:-
SKU ID TYPE NR
-------------------------
HAB1122 O R 201223
Scenario 1
Goods were sold & returned later. It was sold subsequently:-
SKU ID TYPE NR
-------------------------
HAB1122 O N 201211
HAB1122 O R 201223
HAB1122 O N 201245
HAB2233 O N 201263
HAB3344 O N 201303
HAB3344 O R 201341
Using SQL:-
Select SKU, max(NR)
from tableA
where SKU like ‘HAB%’ and ID = ‘O’
group by SKU
Results:-
SKU NR
----------------
HAB1122 201245
HAB2233 201263
HAB3344 201341
This is the correct result as I wish to track down the last NR of the goods sold whether the goods are sold or returned.
If I wish to track down the last NR of goods with status sold only, the expected results should be:-
SKU NR
---------------
HAB1122 201245
HAB2233 201263
HAB3344 is not considered as the goods are returned & not sold subsequently.
How should I change the SQL?
Try this:
This is using Oracle. You didn’t indicate your system so the
havingmay not work specifically on yours but an equivalent will.