1

我有以下情况

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 

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

4

2 回答 2

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)
于 2013-04-17T20:08:35.953 回答
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 演示

于 2013-04-17T20:19:10.063 回答