获取SQL中的行直到列的总和(购买数量)超过结算库存数量

时间:2017-08-28 18:09:36

标签: sql sql-server

我有两张桌子。购买表和结算股票表。

购买表

enter image description here

AND CLOSING STOCK TABLE

enter image description here

我想根据Transaction_Date desc返回购买表中的所有行,直到总和(Purchase_qty)超过CLOSING STOCK TABLE表中的Closing_Stock。

假设对于购买表中的Material_Code AB01,closing_stock在CLOSING STOCK TABLE表中为42。在这种情况下,返回的行将如下所示

enter image description here

正如您所见,前4条记录的总和(Purchase_qty)为43,因此超过42.我不想显示最后一列。因此,当sum(Purchase_qty)超过closing_stock停在那里时,逻辑将是。

我尝试了以下查询但是没有达到结果。任何投入都受到高度赞赏。

SELECT A.Material_Code,A.Transaction_Date, A.Purchase_qty, 
sum(A.Purchase_qty) OVER (ORDER BY Material_Code) AS total 
from Purchase A 
left join Closing_Stock B ON
A.Material_Code = B.Material_Code
where A.Purchase_qty <= B.Closing_Stock
order by A.Transaction_Date desc

2 个答案:

答案 0 :(得分:2)

你很近:

select csp.*
from (select cs.Material_Code, p.Transaction_Date, p.Purchase_qty, 
             sum(p.Purchase_qty) OVER (ORDER BY cs.Material_Code) AS running_qty,
             cs.closing_stock
      from closing_stock cs left join
           Purchase p
           on cs.Material_Code = p.Material_Code
     ) csp
where running_qty - Purchase_qty < closing_stock
order by Transaction_Date desc;

注意:这使您可以获得超过结算库存的第一笔交易。如果您希望最后一个小于该值,请忽略- Purchase_qty

答案 1 :(得分:0)

在“row id”= 2(在购买表中),我们可以看到“Purchase_qty”= 12,但在结果表中,同一行(id = 2)的Purchase_qty = 17。我想,你在某个地方犯了错误。 在我的例子中,你会在那一行找到“17”。

在这里你有正确的选择:

select Material_Code, Purchase_qty, Transaction_Date 
from Purchase p  
where Transaction_Date >= isnull((
    select max(tr_d) from (
        select Material_Code mt_cod, Transaction_Date tr_d, sum(Purchase_qty) OVER (ORDER BY Transaction_Date desc) AS total
        from Purchase iw
        where iw.Material_Code=p.Material_Code  
    ) as query  
    where total >= (select i.Closing_Stock from Closing_Stock i where i.Material_Code=mt_cod)   
), cast('1900-1-1' as date))
order by 1, 3 desc

我专注于在您的示例中构建所有一个查询,这就是为什么查询似乎有点复杂。如果你可以用几个小的查询(而不是一个)构建它,那么性能会更好。这也取决于你有多大的桌子。

我的查询结果:

Material_Code   Purchase_qty    Transaction_Date
AB01    6   2017-08-30 11:05:00.000
AB01    11  2017-08-30 11:04:00.000
AB01    9   2017-08-30 11:03:00.000
AB01    17  2017-08-30 11:02:00.000
AB05    29  2017-08-30 11:08:00.000
AB05    44  2017-08-30 11:07:00.000
AB05    22  2017-08-30 11:06:00.000

检查我的查询的数据:

create table Purchase(Material_Code varchar(10), Purchase_qty integer, Transaction_Date datetime)
insert Purchase values
('AB01',22,'2017-08-30 11:01:00'),
('AB01',17,'2017-08-30 11:02:00'),
('AB01',9 ,'2017-08-30 11:03:00'),
('AB01',11,'2017-08-30 11:04:00'),
('AB01', 6,'2017-08-30 11:05:00'),
('AB05',22,'2017-08-30 11:06:00'),
('AB05',44,'2017-08-30 11:07:00'),
('AB05',29,'2017-08-30 11:08:00')

create table Closing_Stock(Material_Code varchar(10),Closing_Stock integer)
insert Closing_Stock values
('AB01',42),
('AB05',142)