我有一个文章表,其中保存了每个文章的当前库存。我需要知道最后的日期,当新的库存到达后,耗尽了该特定文章的库存。
桌子看起来像这样。
+-----------+-----------------+-------+
| 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。然后新的库存到来,并在9/1/2012 09:56再次达到0。因此,结果应该显示最后一个按ArticleID分组的空股票之后的第一个日期。ArticleID 2没有0分,所以显示了第一个库存日期。
我需要一个可以与其他查询连接的结果集。因此,存储过程对我不起作用。
发布于 2012-10-04 16:13:31
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=1https://stackoverflow.com/questions/12722728
复制相似问题