2012-10-16 68 views
0

我有三個表,其中顯着字段用連字號標記。 如何使用MAX invoiceDate更新所有Customer.MostRecentGiftCardPurchaseAmount與發票中的Customergiftcardpurchase.Amount?SQL服務器更新與第二個表的值與第三個表的最大值相關

Customer 
-pk customerID 
-Money MostRecentGiftCardPurchaseAmount 
Customergiftcardpurchase 
-fk customerID 
-fk invoiceID 
-Money amount 
Invoice 
-pk invoiceID 
-Date invoiceDate 

回答

1

嘗試:

update Customer set 
    MostRecentGiftCardPurchaseAmount = mrp.amount 
from 
    Customer c 
    inner join (
     select lp.customerID, lp.amount 
     from 
      Customergiftcardpurchase lp 
      inner join Invoice li 
       on lp.customerID = li.customerID 
      inner join (
       select p.customerID, max(i.invoiceDate) as MaxInvoiceDate 
       from 
        Customergiftcardpurchase p 
        inner join Invoice i 
         on p.InvoiceId = i.InvoiceId 
       group by p.customerID 
      ) as md 
       on lp.customerID = md.customerID 
       and li.invoiceDate = md.MaxInvoiceDate 
    ) as mrp 
     on c.customerID = mrp.customerID 
0

使用子查詢:

Update c Set 
    MostRecentGiftCardPurchaseAmount = 
    (Select Amount 
     From Customergiftcardpurchase p 
      Join Invoice I 
      On I.invoiceId = p.invoiceId 
       And i.invoiceDate = 
        (Select Max(invoiceDate) 
        From Customergiftcardpurchase c2 
         Join Invoice I2 On I2.invoiceId = c2.invoiceId 
        Where customerID = c.customerID) 
     Where customerID = c.customerID) 
From Customer c 
相關問題