想象一下,我在SqlServer中有以下3个表:
Customer (CustomerID, FirstName, LastName)
Address (AddressID, CustomerID, Line1, City, State)
Product (ProductID, CustomerID, Description)
客户可以拥有多个送货地址和多种产品。
我想要做的是列出最新地址记录确定州的每个州的客户数量。例如“每个州有多少客户上次收到产品?”。因此,我对客户以前的任何地址记录都不感兴趣,只对最近的地址记录感兴趣(由AddressID确定)。
State | Number of Customers
--------------------------
CA | 32
GA | 12
TX | 0
OH | 18
我通常会这样做:
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
WHERE p.ProductID = 101
GROUP BY a.State
但是,由于客户可能有多个地址,客户只会被计入最新地址记录的状态吗?
P.S。以上纯粹是一个示例场景,可以很容易地解释我想要实现的连接,而不是反映实际的系统设计。
答案 0 :(得分:85)
试试这个:
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
答案 1 :(得分:2)
如果没有Orders和OrderDetails表,我不知道如何做到这一点。 Orders表将包含CustomerID ShippingDate和ShipToAddressID,OrderDetails将包含OrderID和ProductID。然后,您需要一个嵌套查询来确定最近的订单(以及最近的地址),将其加入订单详细信息以获取订购的产品,然后过滤您关注的产品。
答案 2 :(得分:1)
您也可以尝试(假设我正确记住了我的SQLServer语法):
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