Hi @Y.N
if I can use cross apply to simplify this query
Yes, you can use Cross Apply here.
SELECT *
FROM #demo t1 CROSS APPLY(SELECT SUM(QTY) AS TotalQTY FROM #demo t2 WHERE t1.ItemId = t2.ItemID GROUP BY ItemId)C
If you want to simplify query, you could also try this:
SELECT *,SUM(QTY)OVER(PARTITION BY ItemID)AS TotalQTY
FROM #demo
Best regards, Cosmog Hong
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.