获取使用SQL实现配额的记录

在“实现配额”下面的记录是30:

ContractNos   Sale    SaleDate    Agent
    1         10      01/01/16     A
    2         20      01/10/16     A
    3         20      01/10/16     A
    4         10      01/11/16     A
    5         40      01/20/16     B
    6         20      01/21/16     C
    7         30      01/22/16     C
    8         10      01/23/16     C

如何获得销售达到的每个代理商的记录,即SaleDate Ascending的30个订单的特定配额.理想的结果必须是这样的:

ContractNos   Sale    SaleDate    Agent
    1         10      01/01/16     A  -> ADD THIS
    2         20      01/10/16     A  -> RECORD = 30 achieved the quota
    3         20      01/10/16     A     
    4         10      01/11/16     A
    5         40      01/20/16     B  -> Quota is achieved which is 30
    6         20      01/21/16     C  -> ADD THIS
    7         30      01/22/16     C  -> RECORD = 50 achieved the quota 
    8         10      01/23/16     C

最终结果

ContractNos   Sale    SaleDate    Agent
    1         10      01/01/16     A
    2         20      01/10/16     A
    5         40      01/20/16     B
    6         20      01/21/16     C
    7         30      01/22/16     C

最佳答案 不幸的是,Sql Server 2008不支持Sum()Over(order by)窗口函数来计算运行总计.

使用相关子查询方法计算运行总计

试试这个

SELECT ContractNos,
       Sale,
       SaleDate,
       Agent
FROM   (SELECT (SELECT Sum([Sale])
                FROM   yourtable  b
                WHERE  a.[Agent] = b.[Agent]
                       AND a.[ContractNos] >= b.[ContractNos]) run_sum,*
        FROM   yourtable a) c
WHERE  run_sum - sale < 30 

或使用Cross Apply

SELECT ContractNos,
       Sale,
       SaleDate,
       Agent
FROM   (SELECT *
        FROM   yourtable a
               CROSS apply (SELECT Sum([Sale])
                            FROM   yourtable b
                            WHERE  a.[Agent] = b.[Agent]
                                   AND a.[ContractNos] >= b.[ContractNos]) c(run_sum)) a
WHERE  run_sum - sale < 30 

对于Sql Server 2012,请使用此方法

SELECT ContractNos,
           Sale,
           SaleDate,
           Agent
FROM   (SELECT Sum([Sale])OVER(partition BY [Agent] ORDER BY [ContractNos]) run_sum,*
        FROM   yourtable) a
WHERE  run_sum - sale < 30 
点赞