sql server join并选择前1个

时间:2018-12-05 12:10:36

标签: sql-server tsql

我有一个客户表和一个地址表,每个客户在地址表中应该有多个地址 我需要一个存储过程来从地址表的顶部选择客户详细信息及其地址 选择客户的参数是companyID

SELECT top 1  s.Addr1 as ShipAddress_Addr1,s.Addr2 as  ShipAddress_Addr2,s.Addr3 as ShipAddress_Addr3,
    s.Addr4 as ShipAddress_Addr4,s.Addr5 as ShipAddress_Addr5,
    s.City as ShipAddress_City,s.[state] as ShipAddress_State,s.PostalCode as ShipAddress_PostalCode,
    s.Country as ShipAddress_Country,s.Note as ShipAddress_Note ,c.CustomerID,c.[TimeCreated], c.[FullName],c.FirstName,c.LastName,c.Phone, c.Email, 
    c.BillAddress_Addr1, c.[BillAddress_Addr2],c. [BillAddress_Addr3],c. [BillAddress_Addr4],c.[BillAddress_Addr5],
     c.BillAddress_City,c.BillAddress_State,c.BillAddress_PostalCode,c.BillAddress_Country,c.BillAddress_Note
        FROM   Customer c left join [dbo].[CustomerShipToAddress] s on s.customerListID=c.CustomerID    
    WHERE c.IsActive = 1 and c.CompanyID = @CompanyID

2 个答案:

答案 0 :(得分:2)

您可以像这样outer apply为每个客户提供最新地址:

select c.customerid, c.name, c.accno, c.txnid, ta.add1, ta.add2
from customertable c
outer apply (select top 1 a.add1, a.add2 from addresstable a where a.customerid = c.customerid order by a.addressid desc) ta

外部的子查询始终为每个客户返回0或1行,因此当您与customertable联接时,不会导致行的重复。

答案 1 :(得分:0)

SELECT TOP 1, c.customerid, c.name, a.add1  FROM customertable c, addresstable a WHERE c.customerid == a.customerid 

这将基本上返回第一行。这就是您要的,但我想的不是您的意思。

如果要查找此信息以供特定客户使用

SELECT TOP 1, c.customerid, c.name, a.add1  FROM customertable c, addresstable a WHERE c.customerid == a.customerid AND c.customerid == "yourcustomerid"

甚至

SELECT c.customerid, c.name, DISTINCT a.add1  FROM customertable c, addresstable a WHERE c.customerid == a.customerid