首页 > 解决方案 > 子查询返回超过 1 个值。如何向列添加更多值?

问题描述

我正在尝试返回一个查询(sql server 和 oracle),每列由不同的查询组成。所以名为“presentes”的第一列是:

SELECT TABLE1.NAME FROM TABLE1 WHERE TABLE1.SESSION = 92

第二列称为“justificados”是:

SELECT TABLE2.NAME FROM TABLE2 WHERE TABLE2.SESSION = 92 AND TABLE2.DATE > '[somedateGoesHere]'

第三列称为“ausentes”是:

SELECT TABLE3.NAME FROM TABLE3 WHERE TABLE3.SESSION = 92

所以我试图把所有这些信息放在一个查询中,比如:

SELECT (SELECT TABLE1.NAME FROM TABLE1 WHERE TABLE1.SESSION = 92) AS presentes,
(SELECT TABLE2.NAME FROM TABLE2 WHERE TABLE2.SESSION = 92 AND TABLE2.DATE > '[somedateGoesHere]') as justificados,
(SELECT TABLE3.NAME FROM TABLE3 WHERE TABLE3.SESSION = 92) as ausentes

这个想法是返回这样的:

预期查询

但我收到此错误:

子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

我知道这是因为第三列的值超过 1 个。但是如何将“null”值添加到其他列来修复它?

标签: sql

解决方案


您可以使用row_number()with union all& 进行条件聚合:

select max(case when tb = 'table1' then name end) as presentes,
       max(case when tb = 'table2' then name end) as justificados,
       max(case when tb = 'table3' then name end) as ausentes
from (select 'table1' as tb, name, row_number() over (order by (select 1)) as seq
      from table1 
      where SESSION = 92 
      union all
      select 'table2', name, row_number() over (order by (select 1))  
      from table2
      where SESSION = 92 AND DATE > '[somedateGoesHere]' 
      union all
      select 'table3', name, row_number() over (order by (select 1))  
      from table3
      where SESSION = 92
     ) t
group by seq;

推荐阅读