在连接语句中选择Top 1

时间:2016-12-08 07:51:52

标签: sql join

对不起,如果有人提出这个问题但我在发布之前先尝试寻找答案。我们使用第三方产品,允许我对我的后端sql服务器运行查询,并想知道是否有可能在有特定匹配时返回单行而不是当前查询返回多行的相同的数据?

我目前获得了"客户经理'的多个数据。来自同一公司的vt.role_desc的选择,其中某人在该客户端的数据库中输入了多个条目。如果有一个"客户经理'我很乐意加入一行。为该角色提供,并且仍然加入它在加入表时找到的其他角色。

以下是我的原始查询,它返回vt.role_desc中的所有角色,但也列出了为该公司列出2个客户经理的更多行。

    select NEWID() AS 'id',
  co.Owner_ID,
 co.Company_RecID,    
  co.Company_ID,     
  co.Company_Name,    
  co.Delete_Flag AS 'Deleted',    
  ca.Address_Line1,    
  ca.Address_Line2,    
  ca.City,    
  ca.State_ID,    
  ca.Zip,    
  ca.PhoneNbr,    
  co.Account_Nbr,     
  co.Delete_Flag, 
  co.date_deleted,     
  co.deleted_by,    
  co.Owner_Level_RecID,    
  vt.role_desc AS 'Role',    
  cty.Description AS 'Type',    
  ca.default_flag AS 'Primary Site',    
  s.Description AS 'Company Status',    
  ISNULL(vt.First_Name, '') + ' ' + ISNULL(vt.Last_Name, '') AS 'Team member'    
from company co inner join    
  dbo.Company_Address AS ca ON ca.Company_RecID = co.Company_RecID    
  left join dbo.company_team AS ct ON co.Company_RecID = ct.Company_RecID    
  left join dbo.v_companyteam_list AS vt on ct.Company_Team_RecID = 
vt.Company_Team_RecID    
  inner join dbo.Company_Type AS cty on co.Company_type_RecID = cty.Company_type_RecID    
  left join dbo.Company_Status AS s on co.Company_Status_RecID = s.Company_Status_RecID    
  Where ca.default_flag='True' 

我尝试了以下更改,但它没有工作,因为它将所有行中的数据保留为空白,除非它是'客户经理'

from company co inner join    
  dbo.Company_Address AS ca ON ca.Company_RecID = co.Company_RecID    
  left join dbo.company_team AS ct ON co.Company_RecID = ct.Company_RecID

  left join (select top 1 * from dbo.v_companyteam_list where role_desc='Account Manager') AS vt on ct.Company_Team_RecID = vt.Company_Team_RecID    
  inner join dbo.Company_Type AS cty on co.Company_type_RecID = cty.Company_type_RecID    
  left join dbo.Company_Status AS s on co.Company_Status_RecID = s.Company_Status_RecID    
  Where ca.default_flag='True'

感谢您对此的任何帮助

0 个答案:

没有答案