如何使用多列作为条件对行进行求和

时间:2016-09-06 15:15:44

标签: sql sql-server-2012

我有一个伪入站出站库存问题,我有物料通过PO进入仓库。然后,该物料通过TRSFR转移到另一个仓库。增加的复杂性是lbs可以通过另一个TRSFR再次转移到不同的仓库。

我想要解决的主要问题是跟踪从原始PO转移的lbs,并使用其volumeLBs跟随这些lbs到后续TRSFR,以限制可以从PurchaseID转移到后续TRSFR的lbs数量。此外,我希望一旦新的PO进入该仓库,计算将重新开始。

此表:

enter image description here

是我希望仅针对一种产品看到的示例。仓库AB的这个时间跨度中有2个PO,发生了多个TRSFR(表格的文字如下):

productkey| PurchaseID| ActivityType| Into_WHKey| From_WHKey| PurchaseDate| volumeLBs| TRSFRed_Lbs| How TRSFRed_Lbs should be found
       123|        001|           PO|         AB|           |     1/6/2016|    21,000|      16,000| (Found by summing the volumeLBs of future PurchaseIDs whose ActivityType = TRSFR and From_Whkey = the Into_WHKey of this PurchaseID and stopping the calculation when there is another 'PO' ActivityType for the same Into_WHKey... the extro 1,000 comes from a TRSFR that was applied to a later PO but had leftover volume)  
       123|        002|        TRSFR|         CD|         AB|     1/8/2016|     5,000|       4,000| (Found by summing the volumeLBs of future PurchaseIDs whose ActivityType = TRSFR and From_Whkey = the Into_WHKey of this PurchaseID and stopping the calculation when there is another 'PO' ActivityType for the same Into_WHKey)  
       123|        003|        TRSFR|         EF|         CD|    1/14/2016|     4,000|          - | ("0" Since there are no future PurcahseIDs whose ActivityType = TRSFR and From_WhKey = the Into_WHKey of this PurcahseID  
       123|        004|        TRSFR|         CD|         AB|    1/15/2016|    10,000|       7,000|  
       123|        005|           PO|         AB|           |     3/6/2016|    14,000|      14,000| (Limited to 14,000 because that is all that is available from this PurchaseID, the extro 1,000 will be applied to an earlier PO)  
       123|        006|        TRSFR|         CD|         AB|    3/16/2016|    15,000|          - |  (14,000 applied to PO dated 3/6/2016, 1,000 applied to PO dated 1/6/2016)
       123|        007|        TRSFR|         GH|         CD|    5/26/2016|     7,000|          - |  

我从名为#All_Data的临时表中提取所有这些数据。这是我写的代码。

exec spDropTable '#ApplyTRSFRs'  
select
    a.productkey  
    ,a.PurchaseID  
    ,a.ActivityType  
    ,a.Into_WHKey  
    ,a.PurchaseID  
    ,a.ActivityType  
    ,a.Into_WHKey  
    ,a.From_WhKey  
    ,a.PurchaseDate  
    ,a.volumeLBs  
    ,case when a.activitytype = 'PO' then lead(a.volumeLBs,1,0) Over (Partition By (a.productkey) Order by a.purchaseorderdate)  
        when a.activitytype = 'TRSFR' then lead(a.volumeLBs,1,0) Over (Partition By (a.productkey) Order by a.purchaseorderdate)  
        else '0'  
        end as TRSFRed_Lbs  

into #ApplyTRSFRs  
from #AllData a  

我需要帮助的主要领域是:
1.限制可以从PO转移的lbs的数量(通过使用其volumeLBs作为最大值),以及
2.一旦发出新的采购订单,只使用新的采购单从-once转移lbs,即新的采购单已经全部转移了lbs,然后可以返回并从旧的采购单转移lbs(如果任何旧PO上仍有lbs可用。

0 个答案:

没有答案