If you are using sql server 2012 and above, you can use this script.
;WITH CTE AS (
SELECT PK_TRXNO, FK_iwItems, qty,
total = SUM(qty) OVER( PARTITION BY FK_iwItems ORDER BY PK_TRXNO DESC ROWS UNBOUNDED PRECEDING )
FROM @MyTable
)
, CTE2 AS (
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY (CASE WHEN total > 40 THEN 1 ELSE 0 END) ORDER BY PK_TRXNO DESC)
FROM CTE
)
SELECT * FROM CTE2
WHERE total <= 40 OR ( total> 40 AND RN = 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.