日期:2014-05-16  浏览次数:20546 次

【100分】有一定难度的分组筛选查询问题,高手速来围观帮忙啊!!!!
本帖最后由 foren_whb 于 2014-05-07 17:46:40 编辑

srcData--复杂查询得到的数据,所以不要说下面数据结构不合理
-------------------------------------------------------------------------------------
id ProductId StockNum EnterTime enterNum
12 100003 22 2014-04-28 00:00:00 10
23 100003 22 2014-04-27 00:00:00 5
41 100003 22 2014-04-25 00:00:00 18
56 100003 22 2014-04-21 00:00:00 10
64 100003 22 2014-04-19 00:00:00 8
75 100003 22 2014-04-13 00:00:00 10
97 100003 22 2014-04-07 00:00:00 5
132 100006 45 2014-05-02 00:00:00 20
163 100006 45 2014-04-28 00:00:00 15
231 100006 45 2014-04-24 00:00:00 5
468 100006 45 2014-04-23 00:00:00 5
532 100006 45 2014-04-20 00:00:00 10
562 100006 45 2014-04-19 00:00:00 15
644 100006 45 2014-04-16 00:00:00 10
687 100006 45 2014-04-15 00:00:00 5
763 100008 12 2014-04-17 00:00:00 5
796 100008 12 2014-04-15 00:00:00 10
803 100008 12 2014-04-15 00:00:00 5
825 100008 12 2014-04-11 00:00:00 15
846 100008 12 2014-04-09 00:00:00 10
867 100008 12 2014-04-02 00:00:00 5

--需要得到的数据
--------------------------------------------------------------------------------------------
id ProductId StockNum EnterTime enterNum
12 100003 22 2014-04-28 00:00:00 10
23 100003 22 2014-04-27 00:00:00 5
41 100003 22 2014-04-25 00:00:00 18
132 100006 45 2014-05-02 00:00:00 20
163 100006 45 2014-04-28 00:00:00 15
231 100006 45 2014-04-24 00:00:00 5
458 100006 45 2014-04-23 00:00:00 5
763 100008 12 2014-04-17 00:00:00 5
796 100008 12 2014-04-15 00:00:00 10

--规则是,根据ProductId分组,按时间降序排列,依次累加入库数量,
--如果达到或超出库存数量,则停止,丢掉之后的数据,开始查找下一个分组
--求高手赐教


------解决方案--------------------

with a(id,ProductId,StockNum,EnterTime,enterNum)as(
select 12,100003,22,'2014-04-28 00:00:00',10 union
select 23,100003,22,'2014-04-27 00:00:00',5 union
select 41,100003,22,'2014-04-25 00:00:00',18 union
select 56,100003,22,'2014-04-21 00:00:00',10 union
select 64,100003,22,'2014-04-19 00:00:00',8 union
select 75,100003,22,'2014-04-13 00:00:00',10 union
select 97,100003,22,'2014-04-07 00:00:00',5 union
select 132,100006,45,'2014-05-02 00:00:00',20 union
select 163,100006,45,'2014-04-28 00:00:00',15 union
select 231,100006,45,'2014-04-24 00:00:00',5 union
select 468,100006,45,'2014-04-23 00:00:00',5 union
select 532,100006,45,'2014-04-20 00:00:00',10 union
select 562,100006,45,'2014-04-19 00:00:00',15 union
select 644,100006,45,'2014-04-16 00:00:00',10 union
select 687,100006,45,'2014-04-15 00:00:00',5 union
select 763,100008,12,'2014-04-17 00:00:00',5 union
select 796,100008,12,'2014-04-15 00:00:00',10 union 
select 803,100008,12,'2014-04-15 00:00:00',5 union
select 825,100008,12,'2014-04-11 00:00:00',15 union
select 846,100008,12,'2014-04-09 00:00:00',10 union
select 867,100008,12,'2014-04-02 00:00:00',5)
, b as(
select *
,(select SUM(enternum) from a where b.ProductId=ProductId an