sql server update,其中第二个表值与第三个表的max相关

时间:2012-10-16 17:36:55

标签: sql sql-server

我有三个表,其中重要字段标有连字符。 如何使用带有MAX invoiceDate的Invoice中的Customergiftcardpurchase.Amount更新所有Customer.MostRecentGiftCardPurchaseAmount?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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