
I have modified the query to consider even if we have more than 2 rows for an item..
create table itemtest
(item int, quantity int, oldquantity int,canceled bit)
INSERT INTO itemtest VALUES (207,12,6,0)
INSERT INTO itemtest VALUES (208,5,2,0)
INSERT INTO itemtest VALUES (207,4,0,1)
INSERT INTO itemtest VALUES (207,2,0,0)
SELECT * FROM itemtest
;with cte as
(select item,
Sum(quantity) as quantity,
Sum(oldquantity) as oldquantity,
canceled from itemtest group BY item,canceled )
--the above cte will group items based on itemid and canceled. Also we sum both the quantity and old quantity
select i1.item, case WHEN i2.canceled=1 THEN (i1.quantity-i1.oldquantity-i2.quantity)
ELSE i1.quantity-i1.oldquantity end as effect from cte i1
INNER JOIN cte i2 on i1.item=i2.item
WHERE i1.canceled=0 AND i2.canceled=1
UNION
SELECT item,(quantity-oldquantity) as effect FROM cte where item not IN (SELECT item from cte where canceled=1)
--From the Cte, we do an equijoin and considering only canceled items, we add quantity+old quantity of not canceled item and from that subtract quantity of the item which is canceled)
--Added an union because the first one will return you only the item has a canceled row, for other items for which all rows are active, are obtained from second query
The output will be
item effect
207 4
208 3
Sarithapraveen, if this helps please login to Mark As Answer. | Alert Moderator