简体   繁体   中英

Select the matching/sum up total in SQL Server

I want to get all the id's that matches/sum up my total qty.

Example if my total qty is 40 then my query will stops until it sums up all the qty at exactly or greater than 40.

See screenshots

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM