我在查询中排名前1位时遇到问题

时间:2018-04-11 16:12:11

标签: sql sql-server

我有三张桌子表:

Customers 
(PK CustomerID, 
FirstName, 
LastName, 
CreatedDate, 
etc)

CustomerLocations 
(PK CustomerLocationID, 
CustomerID, 
LocationID)

Locations 
(PK LocationID,
 StreetAddress1, StreetAddress2, City, State, Zip, Country, 
CreatedDate, etc).

我需要编写一个查询来返回CustomerID,它们的名字和姓氏,以及最近创建的位置的地址字段,但是我在加入{{1}时遇到问题} table。

供参考:

CustomerLocations

当我只想让每个客户显示最近创建的位置字段时,上面显然会导致每个客户重复行。

2 个答案:

答案 0 :(得分:0)

您可以将第二个和第三个表移动到按降序排序的子查询,并使用TOP 1获取最新位置:

SELECT c.CustomerID, c.FirstName + ' ' + c.LastName as CustomerName,
       loc.StreetAddress1, loc.StreetAddress2, loc.City, loc.State, loc.Zip, loc.Country
FROM Customers c
LEFT JOIN (SELECT TOP 1 l.StreetAddress1, l.StreetAddress2,
                        l.City, l.State, l.Zip, l.Country
           FROM CustomerLocations cl
           LEFT JOIN Locations l ON cl.LocationID = l.LocationID
           ORDER BY l.CreatedDate DESC) loc
       ON loc.CustomerID = cl.CustomerID

答案 1 :(得分:0)

row_number()是解决此问题的典型方法:

SELECT c.CustomerID, c.FirstName + ' ' + c.LastName as CustomerName,
       cl.StreetAddress1, cl. StreetAddress2, cl.City, cl.State, cl.Zip, cl.Country
FROM Customers c LEFT JOIN
     (SELECT cl.CustomerId, l.*,
             ROW_NUMBER() OVER (PARTITION BY cl.CustomerId ORDER BY l.CreatedDate DESC) as seqnum
      FROM CustomerLocations cl JOIN
           Locations l 
           ON cl.LocationID = l.LocationID
     ) cl
     ON c.CustomerID = cl.CustomerID AND cl.seqnum = 1;

作为一个注释,您应该在联结表(CreatedDate)中保留CustomerLocations。这将简化查询并有效地完成同样的事情。