Most recent record in a left join

前端 未结 3 1096
执笔经年
执笔经年 2020-12-23 09:06

Imagine I have the following 3 tables in SqlServer:

Customer (CustomerID, FirstName, LastName)
Address (AddressID, CustomerID, Line1, City, State)
Product (P         


        
相关标签:
3条回答
  • 2020-12-23 09:56

    I don't see how you can do this without having Orders and OrderDetails tables. The Orders table would include the CustomerID ShippingDate and ShipToAddressID, and OrderDetails would have the OrderID and ProductID. You'll then need a nested query to determine the most recent order (and hence most recent address), join that to the order details to get the products ordered, then filter on the product you care about.

    0 讨论(0)
  • 2020-12-23 09:57

    Try this:

    SELECT a.State, count(c.CustomerID)
    FROM Product p
    INNER JOIN Customer c ON c.CustomerID = p.CustomerID
    LEFT JOIN Address a ON a.CustomerID = c.CustomerID 
          AND a.AddressID = 
            (
               SELECT MAX(AddressID) 
               FROM Address z 
               WHERE z.CustomerID = a.CustomerID
            )
    WHERE p.ProductID = 101
    GROUP BY a.State
    
    0 讨论(0)
  • 2020-12-23 10:07

    You could also try (assuming I remember my SQLServer syntax correctly):

    SELECT state, count(customer_id)
    FROM (
        SELECT
            p.customer_id
            , (SELECT TOP 1 State FROM Address WHERE Address.CustomerID = p.CustomerID ORDER BY Address.ID DESC) state
        FROM Product p
        WHERE p.ProductID = 101)
    GROUP BY state
    
    0 讨论(0)
提交回复
热议问题