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

时间:2016-06-27 06:30:42

标签: sql sql-server sql-server-2008-r2

在下面的记录中,实现配额是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获得销售达到某个配额的每个代理商的记录。理想的结果必须是这样的:

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

2 个答案:

答案 0 :(得分:2)

不幸的是Sql Server 2008不支持Sum() Over(order by)窗口函数来计算运行总计。

使用Correlated sub-query method计算运行总计

试试这个

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 

答案 1 :(得分:0)

另一种可能的解决方案是使用连接计算运行总计:

select s1.ContractNos, s1.Sale, s1.SaleDate, s1.Agent
  from sales s1
       left join sales s2
       on s1.ContractNos >= s2.ContractNos and s1.Agent = s2.Agent
 group by s1.ContractNos, s1.Sale, s1.SaleDate, s1.Agent
 having sum(s2.sale) - s1.sale < 30 
 order by s1.ContractNos