MS SQL 2008 join - 从许多结果中选择一个

fra*_*ais 4 sql join sql-server-2008

我正在尝试运行以下查询,但我不确定如何将其限制为仅一个结果.在下面的查询中,clientcontactid 21901工作的客户端有2个地址,意味着返回2个结果.

查询:

select  cc.contactpersonid,
    cc.clientcontactid,
    ad.city,
    ad.addressid
from SavedList sl
inner join ClientContacts cc on cc.ContactPersonId = sl.ObjectId
inner join Clients c on c.ClientID = cc.ClientId
inner join Address ad on c.ClientID = ad.ObjectId
where sl.SavedListId = 2117
Run Code Online (Sandbox Code Playgroud)

结果:

contactpersonid clientcontactid city    addressid
87934           21901                   145186
87934           21901           London  1130705
89778           17275           Leeds   145368
Run Code Online (Sandbox Code Playgroud)

我需要为客户联系21901返回其中一个结果,优先级是其中包含城市的结果.我已经尝试过选择top(1),但我认为这取决于连接强制多个记录.有关如何仅返回1个结果的任何帮助,以及如何控制它将受到高度赞赏!

谢谢

Iva*_*n G 6

尝试:

;WITH a AS (
select  cc.contactpersonid,
    cc.clientcontactid,
    ad.city,
    ad.addressid,
    ROW_NUMBER() OVER (PARTITION BY cc.clientcontactid ORDER BY ad.city DESC) AS RowNum
    from SavedList sl
    inner join ClientContacts cc on cc.ContactPersonId = sl.ObjectId
    inner join Clients c on c.ClientID = cc.ClientId
    inner join Address ad on c.ClientID = ad.ObjectId
    where sl.SavedListId = 2117
)

SELECT  *
FROM    a
WHERE   RowNum = 1
Run Code Online (Sandbox Code Playgroud)