sql - 子查询返回超过 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”值添加到其他列来修复它?
解决方案
您可以使用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;
推荐阅读
- java - Sharedpreference.edit() 在 JUnit 测试 + Mockito 中给出 NullPointerException
- android - 为什么让移动应用程序向 ELK 发送崩溃日志不流行
- pytorch - 在 PyTorch 中,逐行与矩阵中每隔一行的元素批量矩阵乘法
- python - 如何使用 youtube-dl 在不下载的情况下获取有关视频的信息
- r - 在 r 中添加斜坡函数
- machine-learning - Word2Vec - 具有高交叉验证分数的模型对测试数据表现得非常糟糕
- c - 绕过/切换/选择弱符号
- php - 如何在 Laravel 中创建 3 级深度类别的 URL
- c++ - 在命名空间内定义函数还是限定函数?
- python - 由于 WDDM 模式,不允许将我的 GTX1050 用于 tensorflow/keras