答案 0 :(得分:1)
如果您使用的是sql server 2012及更高版本,则可以使用此脚本。
;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)