日期:2014-05-18 浏览次数:20416 次
--> 测试数据:#PurchaseOrderMaster if object_id('tempdb.dbo.#PurchaseOrderMaster') is not null drop table #PurchaseOrderMaster create table #PurchaseOrderMaster(PurchaseOrderID int, PackageAmount numeric(10,2), InvoiceAmount numeric(10,2)) insert into #PurchaseOrderMaster select 1, 300.00, 100.00 union all select 2, 700.00, 400.00 union all select 3, 500.00, 300.00 --> 测试数据:#PurchaseOrderItem if object_id('tempdb.dbo.#PurchaseOrderItem') is not null drop table #PurchaseOrderItem create table #PurchaseOrderItem(PurchaseOrderItemID int, PurchaseOrderID int, PackageSubTotalAmount numeric(10,2), ProRataPackageSubTotalAmount numeric(10,2)) insert into #PurchaseOrderItem select 1, 1, 100.00, 0.00 union all select 2, 1, 100.00, 0.00 union all select 3, 1, 100.00, 0.00 union all select 4, 2, 500.00, 0.00 union all select 5, 2, 100.00, 0.00 union all select 6, 2, 100.00, 0.00 union all select 7, 3, 100.00, 0.00 union all select 8, 3, 200.00, 0.00 union all select 9, 3, 200.00, 0.00 ;with cte(item,po,ia,maxid,v) as ( select a.PurchaseOrderItemID, a.PurchaseOrderID, b.InvoiceAmount, max(a.PurchaseOrderItemID)over(partition by a.PurchaseOrderID), convert(dec(10,2), PackageSubTotalAmount*InvoiceAmount/PackageAmount) from #PurchaseOrderItem a join #PurchaseOrderMaster b on a.PurchaseOrderID=b.PurchaseOrderID ), v as ( select item, v = case maxid when item then ia-(select sum(v) from cte where po=t.po and item<t.item) else v end from cte t ) update #PurchaseOrderItem set ProRataPackageSubTotalAmount = v from #PurchaseOrderItem, v where PurchaseOrderItemID=item select * from #PurchaseOrderItem /* PurchaseOrderItemID PurchaseOrderID PackageSubTotalAmount ProRataPackageSubTotalAmount ------------------- --------------- --------------------------------------- --------------------------------------- 1 1 100.00 33.33 2 1 100.00 33.33 3 1