Update Query with Correlated Subquery

后端 未结 2 1723
日久生厌
日久生厌 2021-01-23 07:51

I\'m trying to convert a Foxpro application into .NET. As part of that conversion I\'m converting the data from DBF tables to Sql server.

I need to come up with a coupl

相关标签:
2条回答
  • 2021-01-23 08:13

    Although I think the JOIN criteria is highly unlikely, it looks like you're trying to do this?

    EDIT: I've modified the JOIN criteria but this is what you're after. Grouping By columns that are OR'd is odd.

    ;WITH MinOrderDates AS
    (
        SELECT   CustID 
                ,OrderDate  = MIN(OrderDate)
        FROM Orders
        GROUP BY CustID
    )
    
    UPDATE C
    SET FirstOrderDate = MIN(O.OrderDate)
    FROM Customers      C
    JOIN MinOrderDates  O   ON C.Id = O.CustID
    

    This is what your query would look like with the ORs

    ;WITH MinOrderDates AS
    (
        SELECT   ShipperId
                ,PickupId
                ,ConsigneeId
                ,DeliveryId
                .BillingId
                ,OrderDate  = MIN(OrderDate)
        FROM Orders
        GROUP BY ShipperId
                ,PickupId
                ,ConsigneeId
                ,DeliveryId
                .BillingId
    )
    
    UPDATE C
    SET FirstOrderDate = MIN(O.OrderDate)
    FROM Customers      C
    JOIN MinOrderDates  O   ON o.ShipperId     = C.Id or
                               o.PickupId      = C.Id or
                               o.ConsigneeId   = C.Id or
                               o.DeliveryId    = C.Id or
                               o.BillingId     = C.Id 
    

    EDIT: Though I am having a hard time finding fault with your posted syntax.

    0 讨论(0)
  • 2021-01-23 08:16

    Try this

    UPDATE customers
    SET FirstOrderDate = 
    (Select MIN(OrderDate)
    FROM Orders
    WHERE ShipperId = Customers.Id or
    PickupId = Customers.Id or
    ConsigneeId = Customers.Id or
    DeliveryId = Customers.Id or
    BillingId = Customers.Id)
    
    0 讨论(0)
提交回复
热议问题