首页 > 解决方案 > 子查询返回多个值。这是不允许的

问题描述

我正在尝试从不同的表中提取数据并尝试根据日期和客户 ID 获取 golivedata。下面是查询。

select c.customerID,  
       c.CustomerName,  
       cs.ContactName, 
       e.ComponentName, 
       e.ComponentVersion, 
       (
           select ps.GoLiveDate  
           from   Projects ps 
           where  ps.GoLiveDate <= CURRENT_TIMESTAMP 
           and    ps.CustomerID = c.CustomerID
       ) as CurrentGoLiveDate 
from   projects p 
       join customers c    on c.CustomerID = p.CustomerID 
       join contacts cs    on cs.ProjectID = p.ProjectID 
       join Environments e on e.ProjectID  = p.ProjectID 
where  e.ComponentName like 'RP%' 
and    cs.ContactType = 'Account Manager'

但我收到一个错误:

错误图像

标签: sqlsql-server

解决方案


预期的结果会有所帮助,您可以利用存在并以这种方式获得价值。我假设您正在寻找至少有一行的客户(如果有多行,同一客户有多个上线日期),上线日期小于当前时间戳。

我认为这也可以帮助您获得预期的输出。

select c.customerID,  c.CustomerName,  cs.ContactName, e.ComponentName, e.ComponentVersion,
  ps.GoLiveDate as CurrentGoLiveDate 
 from projects p 
 join customers c on c.CustomerID = p.CustomerID 
 join contacts cs on cs.ProjectID = p.ProjectID
 join Environments e on e.ProjectID = p.ProjectID
  where e.ComponentName like 'RP%' and cs.ContactType= 'Account Manager' 
  and exists (select 1 from Projects ps where  ps.GoLiveDate <= CURRENT_TIMESTAMP and ps.CustomerID = c.CustomerID) 

推荐阅读