Hi @mohamed basha
There is one thing you didn't make clear. If an item(trn_itmsrl) does not have trn_typ=26, then you want to sum all trn_qnty for that item, or not sum and return '0' instead.
If you want to sum all trn_qnty for item that does not have trn_typ=26, then check this :
;WITH CTE AS
(
SELECT trn_itmsrl,MAX(CASE WHEN trn_typ=26 THEN tran_date ELSE '2000/01/01' END) AS LAST_DATETIME
FROM EnterItemsTransaction
GROUP BY trn_itmsrl
)
SELECT T.trn_itmsrl,SUM(T.trn_qnty) AS Total_qnty
FROM EnterItemsTransaction T JOIN CTE C ON T.trn_itmsrl=C.trn_itmsrl AND T.tran_date>=C.LAST_DATETIME
GROUP BY T.trn_itmsrl
If you don't want to sum trn_qnty for item that does not have trn_typ=26, then check this :
;WITH CTE AS
(
SELECT trn_itmsrl,MAX(tran_date) AS LAST_DATETIME
FROM EnterItemsTransaction
WHERE trn_typ=26
GROUP BY trn_itmsrl
)
SELECT T.trn_itmsrl,SUM(CASE WHEN C.trn_itmsrl IS NULL THEN 0 ELSE T.trn_qnty END) AS Total_qnty
FROM EnterItemsTransaction T LEFT JOIN CTE C ON T.trn_itmsrl=C.trn_itmsrl AND T.tran_date>=C.LAST_DATETIME
GROUP BY T.trn_itmsrl
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.