累积计数和日期计数变为负面和正面

时间:2013-04-17 19:59:53

标签: sql-server sql-server-2008

我有以下情况

Date     Amount Item 
6/17/08 208  1 
9/24/08  -48     1 
6/15/09  -160    1 
9/23/09  40      1 

对于相同的项目,我想获得第一次累积金额小于或等于0的日期 如果累积金额后来变为正数,我也想得到它变为正数的日期。

Date     Amount Item Cumulative Amount 
6/17/08   208    1   208 
9/24/08  -48     1       160 
6/15/09  -160    1        0 --This date 
9/23/09  40      1        40 --This date 

有关如何实现这一目标的任何建议?

2 个答案:

答案 0 :(得分:2)

在SQL Server 2012中:

SELECT  date
FROM    (
        SELECT  *,
                SUM(amount) OVER (PARTITION BY item ORDER BY date) AS csum,
                SUM(amount) OVER (PARTITION BY item ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS psum
        FROM    mytable
        ) q
WHERE   (csum <= 0 AND psum > 0)
        OR
        (csum > 0 AND psum <= 0)

在早期版本中:

SELECT  date
FROM    (
        SELECT  *,
                (
                SELECT  SUM(amount)
                FROM    mytable mi
                WHERE   mi.item = m.item
                        AND mi.date < m.date
                ) AS psum
        FROM    mytable m
        ) q
WHERE   (psum + amount <= 0 AND psum > 0)
        OR
        (psum + amount > 0 AND psum <= 0)

答案 1 :(得分:0)

首次变为非正面的日期:

SELECT MIN(t3.Date) AS dateCumAmountTurnsLTEZero
FROM
(SELECT Date, 
 (SELECT SUM(Amount)
  FROM mytable t1
  WHERE t1.Date <= t2.Date) AS cumulativeAmount
 FROM mytable t2) t3
 WHERE t3.cumulativeAmount <= 0

要获得再次变为正数的日期,您可以将此结果注入另一个查询,或者假设您希望在SQL中完成所有操作,它会变得有点毛茸茸!见下文:

SELECT MIN(t6.Date)
FROM
(SELECT Date, 
 (SELECT SUM(Amount)
  FROM mytable t4
  WHERE t4.Date <= t5.Date) AS cumulativeAmount
 FROM mytable t5) t6
WHERE t6.cumulativeAmount >= 0
AND t6.Date >
(SELECT MIN(t3.Date)
 FROM
 (SELECT Date, 
  (SELECT SUM(Amount)
   FROM mytable t1
   WHERE t1.Date <= t2.Date) AS cumulativeAmount
  FROM mytable t2) t3
  WHERE t3.cumulativeAmount <= 0)

请参阅SQL Fiddle Demo