在SQL中使用FIFO更新事务记录

时间:2017-01-22 07:46:42

标签: sql sql-server sql-update

我有接收和运送申请。我正在处理事务表中的这两个进程。在手动接收项目时给出BOE号码,所以所有接收记录都有BOE号码。但是在发货时我没有更新此BOE列。实际上我需要知道这个项目来自哪个BOE(我想使用FIFO)标准。现在我的事务表有很多数据。但我想知道每个BOE有多少项目来了多少项目。

我这样做了查询

select 
    F_lot_number, sum(INq) 'IN', sum(OUTs) 'OUT', sum(BOE) 'BOEcount' 
from 
    (select 
         F_lot_number,
         case 
            when F_Stock_Type = 'IN' then sum(F_qty) 
         end as 'INq',
         case 
            when F_Stock_Type = 'out' and  F_IsBook = '2' then sum(F_qty)  
         end as 'OUTs',
         case 
            when F_Stock_Type = 'IN' 
               then count(distinct F_BillOf_entryNumber) 
         end as 'BOE'
     from 
         T_Tra_Transaction 
     group by 
         F_lot_number, F_Stock_Type, F_IsBook) d 
group by 
    F_lot_number

输出如下:

enter image description here

如果示例

select 
    F_QTY, F_lot_number, F_BillOf_entryNumber 
from 
    T_Tra_Transaction 
where 
    F_lot_number = '150723A151' 
    and F_Stock_Type = 'IN'

select 
    F_QTY, F_lot_number, F_BillOf_entryNumber 
from 
    T_Tra_Transaction 
where 
    F_lot_number = '150723A151' 
    and F_Stock_Type = 'out'

输出如下:

enter image description here

我需要用相应的BOE号码更新所有状态。我怎样才能做到这一点?我需要更新我现有的所有录音机。如果有任何帮助我非常感谢

在我的表格中,我也有transdatetime字段。

我已经检查了其他批号..

select 
    F_QTY, F_lot_number, F_BillOf_entryNumber 
from 
    T_Tra_Transaction 
where 
    F_lot_number = '150919C131' 
    and F_Stock_Type = 'IN'

select 
    F_QTY, F_lot_number, F_BillOf_entryNumber 
from 
    T_Tra_Transaction 
where 
    F_lot_number = '150919C131' 
    and F_Stock_Type = 'out'

但我这样出去了: enter image description here

1 个答案:

答案 0 :(得分:0)

我认为每一批产品总是以与获得的相同数量出售。 所以这个想法只是row_number()正确进出,并从相应的ins更新。未经测试。

update tout
set F_BillOf_entryNumber = tin.F_BillOf_entryNumber 
from (
    select F_QTY, F_lot_number, F_BillOf_entryNumber 
    , rn = row_number() over (partition by F_QTY, F_lot_number order by transdatetime desc)
    from 
        T_Tra_Transaction 
    where 
        F_Stock_Type = 'out'
    ) tout
join (
    select 
        F_QTY, F_lot_number, F_BillOf_entryNumber
        , rn = row_number() over (partition by F_QTY, F_lot_number order by transdatetime desc)
    from 
        T_Tra_Transaction 
    where 
        F_Stock_Type = 'IN'
    ) tin 
    on tout.F_QTY = tin.F_QTY
       and tout.F_lot_number = tin.F_lot_number
       and tout.rn = tin.rn;

修改

我在样本数据上测试了它

create table T_Tra_Transaction(
F_QTY int, F_lot_number int , F_BillOf_entryNumber int,
     transdatetime int, F_Stock_Type varchar(3));
insert  T_Tra_Transaction (F_QTY, F_lot_number, F_BillOf_entryNumber,transdatetime,F_Stock_Type)
values
(10,1,101,200,'IN'),
(20,1,102,201,'IN'),
(20,1,null,200,'out');