跳过子表中的记录

时间:2015-10-12 12:24:58

标签: sql sql-server sql-server-2012

我试图编写查询,即从2个表中选择一些东西。 不幸的是我坚持以下问题:在表格中

Person.BusinessEntityAdress

您将密钥存储到另一个包含人员地址的表,但有些记录有2个或更多个密钥,我的意思是只选择其中一个密钥,然后跳过休息。 我正在使用AdventureWorks2012数据库。 这是一个link,您可以在这里阅读有关此数据库的信息。 到目前为止,这是我的疑问:

SELECT 
    pp.FirstName AS CUS_FirstName,
    pp.FirstName + pp.LastName AS CUS_Name,
    pp.LastName AS CUS_LastName, 
    pa.AddressLine1 AS CUS_AddressLine1, 
    pa.AddressLine2 AS CUS_AddressLine2,
    pp.BusinessEntityID AS CUS_CleanOrgID, --ID klienta
    CUS_SRCOrgID = '0' --ID źródła danych
FROM Person.Person pp
LEFT JOIN Person.BusinessEntityAddress pb
ON pp.BusinessEntityID = pb.BusinessEntityID
LEFT JOIN Person.Address pa
    ON pb.AddressID=pa.AddressID
ORDER BY pp.BusinessEntityID;

1 个答案:

答案 0 :(得分:0)

如果一个BusinessEntityAddress多个BusinessEntityAddress,您可以使用子选择限制为新的最新Person 注:我认为IdBusinessEntityAddress

上的PK
SELECT 
  pp.FirstName AS CUS_FirstName,
  pp.FirstName + pp.LastName AS CUS_Name,
  pp.LastName AS CUS_LastName, 
  pa.AddressLine1 AS CUS_AddressLine1, 
  pa.AddressLine2 AS CUS_AddressLine2,
  pp.BusinessEntityID AS CUS_CleanOrgID, --ID klienta
  CUS_SRCOrgID = '0' --ID źródła danych
FROM Person.Person pp
 LEFT JOIN Person.BusinessEntityAddress pb
  ON pp.BusinessEntityID = pb.BusinessEntityID
    AND NOT EXISTS (SELECT 1 FROM Person.BusinessEntityAddress pb2
                    WHERE pp.BusinessEntityID = pb2.BusinessEntityID
                      AND pb2.Id > pb.Id)
 LEFT JOIN Person.Address pa
  ON pb.AddressID=pa.AddressID
ORDER BY pp.BusinessEntityID;