0

我有一个文章表,其中包含每篇文章的当前库存。在特定文章的库存用完后,我需要知道新库存到货的最后日期。

桌子看起来像这样。

+-----------+-----------------+-------+
| ArticleID |    StockDate    | Stock |
+-----------+-----------------+-------+
|         1 | 1/1/2012 10:15  |   100 |
|         1 | 2/1/2012 13:39  |   -50 |
|         1 | 2/1/2012 15:17  |   -50 |
|         1 | 4/1/2012 08:05  |   100 |
|         2 | 5/1/2012 09:48  |    50 |
|         1 | 6/1/2012 14:21  |   -25 |
|         1 | 7/1/2012 16:01  |    10 |
|         2 | 8/1/2012 13:42  |   -10 |
|         1 | 9/1/2012 09:56  |   -85 |
|         1 | 13/1/2012 08:12 |   100 |
|         1 | 13/1/2012 10:50 |   -15 |
+-----------+-----------------+-------+

输出应如下所示。

+-----------+-----------------+
| ArticleID |    StockDate    |
+-----------+-----------------+
|         2 | 5/1/2012 09:48  |
|         1 | 13/1/2012 08:12 |
+-----------+-----------------+

我是如何得到这个输出的?ArticleID 1 有 100 个库存,但在 2/1/2012 15:17 首次达到 0。然后新的股票到了,它在 2012 年 9 月 1 日 09:56 再次跌至 0。所以结果应该显示按 ArticleID 分组的最后一个空股票之后的第一个日期。ArticleID 2 没有 0 点,因此显示第一个库存日期。

我需要一个可以与其他查询连接的结果集。所以存储过程对我不起作用。

4

1 回答 1

1
select ArticleID,stockdate from 
(
    select t.ArticleID, t.stockdate, ROW_NUMBER() Over (partition by t.articleid order by v.articleid desc, stockdate) rn
    from yourtable t
    left join 
    (
        select ArticleID, MAX(stockdate) as msd from yourtable t1
        cross apply (select sum(stock) as stockrt from yourtable where stockdate<=t1.stockdate and ArticleID=t1.ArticleID) rt
        where stockrt = 0
        group by articleid
    ) v
    on t.ArticleID = v.ArticleID
    and t.stockdate>v.msd
) v
where rn=1
于 2012-10-04T08:13:31.400 回答