2015-01-14 39 views
1

我有兩個表 - 檢查和策略。下面是結構。爲了清楚起見,這是最起碼的結構兩列SQL DIfference

表名:檢查

列: ChequeId。 ChequeNumber, 金額, LASTUPDATED

表名:政策

策略ID, PolicyNumber, ChequeId, 金額, LASTUPDATED

我想有一個查詢返回給我下面的

ChequeNumber,PolicyId,ChequeAmount,PolicyAmount,Difference 

一張支票可以被映射到多個策略(一對多的關係) 現在,如果支票被匹配到說2個政策和這兩個策略的量的總和大於支票金額越大,我應該看到其中的差別,但只適用於第二policy.It的假設,第一政策得到完全匹配的。(或許用最後更新列?)所以輸出將

ChequeNumber PolicyNumber ChequeAmount PolicyAmount Difference  
    1    1    200   100   0 
    1    2    200   200   100 

下面是我自己編寫

SELECT chequeNumber AS chequeNumber 
     ,COALESCE(p.policyNumber, '') AS PolicyNumber 
     ,c.amount AS chequeamount 
     ,p.Amount As PolicyAmount 
     ,(c.Amount) - SUM(p.Amount) OVER (PARTITION BY c.ChequeID) AS Difference 
FROM Cheque c 
LEFT JOIN Policy AS p 
    ON p.ChequeId=c.ChequeId 
GROUP BY chequeNumber, policyNumber,c.amount,p.Amount,c.ChequeID 

這給了我在兩個行(下表)中的差異,而不僅僅是映射的最後一個策略。

ChequeNumber PolicyNumber ChequeAmount PolicyAmount Difference  
    1    1    200   100   -100 
    1    2    200   200   -100 

我正在使用SQL 2008 R2。

+2

[這](http://stackoverflow.com/questions/9420173/sql-subtracting-a-depleting -valu電子行業)這個問題涉及消耗庫存中多個批次的庫存。聽起來像是一個類似的問題。 – HABO

回答

0

由於您使用的是SQL Server 2008中,你已經限制了窗函數的支持,所以你需要一個自聯接:

WITH DATA AS 
(
    SELECT chequeNumber AS chequeNumber 
      ,COALESCE(p.policyNumber, '') AS PolicyNumber 
      ,c.amount AS chequeamount 
      ,p.Amount As PolicyAmount 
      ,P.MovingSum 
    FROM Cheque c 
    LEFT JOIN (SELECT P1.PolicyId 
         ,P1.PolicyNumber 
         ,P1.ChequeId 
         ,P1.Amount 
         ,P1.Amount + COALESCE(P2.Amount, 0) AS MovingSum 
       FROM Policy AS P1 
       LEFT JOIN Policy AS P2 
        ON P1.ChequeId = P2.ChequeId 
        AND P1.PolicyId > P2.PolicyId 
        AND P1.PolicyNumber > P2.PolicyNumber) AS p 
     ON p.ChequeId = c.ChequeId 
    GROUP BY chequeNumber, policyNumber, c.amount, p.Amount, c.ChequeID, p.MovingSum 
) 
SELECT chequeNumber 
     ,PolicyNumber 
     ,chequeamount 
     ,PolicyAmount 
     ,CASE WHEN MovingSum > PolicyAmount THEN MovingSum - chequeamount ELSE 0 END AS Difference 
FROM DATA; 
+0

謝謝,但它仍然給我相同的輸出,雖然現在差異是積極的 –

+0

@RuchinMunjal它解決了你的問題? – dario

0

如果我理解正確的,你需要計算 政策金額之間的差額 - (檢查量 - 考慮到分配已分配給以前的政策量) 是policynumber爲了這應該工作:

SELECT chequeNumber AS chequeNumber 
     ,COALESCE(p.policyNumber, '') AS PolicyNumber 
     ,c.amount AS chequeamount 
     ,p.Amount As PolicyAmount 
     ,p.amount - 
     CASE WHEN 
     (c.Amount - (SELECT SUM(p1.amount) FROM cheque c1 LEFT JOIN policy p1 ON p1.chequeid=c1.chequeid AND p1.policynumber < p.policynumber)) < 0 THEN 0 
     ELSE (c.Amount - (SELECT SUM(p1.amount) FROM cheque c1 LEFT JOIN policy p1 ON p1.chequeid=c1.chequeid AND p1.policynumber < p.policynumber)) END Difference 
FROM Cheque c 
LEFT JOIN Policy AS p 
    ON p.ChequeId=c.ChequeId 
GROUP BY chequeNumber, policyNumber,c.amount,p.Amount,c.ChequeID