子查询返回了多个值。这是不允许的

时间:2019-04-09 02:10:31

标签: sql sql-server

我试图从不同的表中提取数据,并尝试基于日期和客户ID获取g​​olivedata。下面是查询。

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'

但是我遇到一个错误:

error image

5 个答案:

答案 0 :(得分:0)

您正在将子查询的结果用作最终select语句中的值。由于查询返回多个值,因此会出现错误。如果您期望子查询中有多个值,则应该以其他方式设计查询

答案 1 :(得分:0)

您在Select语句中的子查询返回多个记录。

<SafeAreaView>
   <Component1 />
   <Component2 />
</SafeAreaView>

匹配多个行。您需要WHERE ps.GoLiveDate <= CURRENT_TIMESTAMP AND ps.CustomerID = c.CustomerID SELECT TOP 1等。

答案 2 :(得分:0)

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

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

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) 

答案 3 :(得分:0)

看到您发布的图像中有一个TOP 1。我只是在猜测您想要最大的GoLiveDate

select c.customerID,  
       c.CustomerName,  
       cs.ContactName, 
       e.ComponentName, 
       e.ComponentVersion, 
       (
           select MAX(ps.GoLiveDate)   -- Added MAX() here
           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'

答案 4 :(得分:0)

如果您不担心重复的客户,可以使用:

select c.customerID,  
       c.CustomerName,  
       cs.ContactName, 
       e.ComponentName, 
       e.ComponentVersion, 
       x.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 
       join (select ps.GoLiveDate  CurrentGoLiveDate, CustomerID
             from   Projects ps 
             where  ps.GoLiveDate <= CURRENT_TIMESTAMP ) as X on X.CustomerID = c.CustomerID
where  e.ComponentName like 'RP%' 
and    cs.ContactType = 'Account Manager'

在其他情况下,您应该使用TOP 1MAX/MIN