0

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

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

2 回答 2

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
于 2012-10-16T17:48:35.940 回答
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
于 2012-10-16T17:48:25.447 回答