我正在尝试运行以下查询,但不确定如何将其限制为仅一个结果。在下面的查询中,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
结果:
contactpersonid clientcontactid city addressid 87934 21901 145186 87934 21901 London 1130705 89778 17275 Leeds 145368
我需要为客户联系 21901 返回这些结果 之一 ,其中优先考虑的是城市所在的那个。我试过选择 top(1), 但我认为这归结于迫使多条记录返回的联接。对于如何仅返回1个结果以及如何控制该结果的任何帮助,将不胜感激!
谢谢
尝试:
;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