想象一下,我在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
但是,由于客户可能有多个地址,将仅在最近地址记录的状态中对客户进行计数吗?
PS上面仅是一个示例场景,可以轻松地解释我要实现的联接,并且不反映实际的系统设计。
试试这个:
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