如何只获取行< =(数量)Transact-SQL

时间:2018-04-13 15:51:20

标签: sql tsql

您好我最近想要一份报告,我们只能看到小于或等于数量的行

示例

我有这张桌子

USER   QUANTITY
JOHN       2        
JOHN       3        
JOHN       1         
JOHN       3       

我想只显示Total为5的行

它应该显示

USER    QUANTITY    
JOHN       2        
JOHN       3        

我从未尝试过这种查询,我不知道从哪里开始

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的要求,但希望这可以帮助你开始:

模式

DROP TABLE IF EXISTS #YourTable 
CREATE TABLE #YourTable ([USER] VARCHAR(50), QUANTITY INT);
INSERT #YourTable ([USER], QUANTITY) 
VALUES ('JOHN', 2)
    ,('JOHN', 3)
    ,('JOHN', 1)
    ,('JOHN', 1)
    ,('JOHN', 2)
    ,('MICHAEL', 2)
    ,('MICHAEL', 2)
    ,('MICHAEL', 2)
    ,('MICHAEL', 2)

查询

DECLARE @Limit INT = 5

;WITH cte AS (
    SELECT [USER], QUANTITY
        , RunningTotal = SUM(QUANTITY) OVER (PARTITION BY [USER] ORDER BY [USER] ROWS UNBOUNDED PRECEDING)
    FROM #YourTable
)
SELECT [USER], QUANTITY FROM cte 
    WHERE RunningTotal <= @Limit

结果

+---------+----------+
|  USER   | QUANTITY |
+---------+----------+
| JOHN    |        2 |
| JOHN    |        3 |
| MICHAEL |        2 |
| MICHAEL |        2 |
+---------+----------+