sql - 如何在 select 子句中使用子查询和 from 子句中的子查询
问题描述
我尝试查询但得到错误 tt.comp 在上下文中无效。
我认为子查询#1(选择子句)无法访问子查询#2(从子句)或子查询#1 在子查询#2 之前执行。
SELECT grp1
,(select count(distinct tt.comp) as comp
from t as tt
where tt.lamp = 1
and tt.pop = t.pop)
FROM (select ......) as t group by grp1
如何解决。
提前致谢。
解决方案
为什么你在子查询中引用同一个表,我猜你可以简单地使用 CASE 语句 -
SELECT grp1,
COUNT(DISTINCT CASE WHEN lamp = 1 THEN tt.comp END) AS COMP
FROM (select ......) as t
GROUP BY grp1
推荐阅读
- php - PHP错误网页显示通知但不显示错误
- reactjs - 使用 React Router V4 时如何防止组件立即卸载
- node.js - Mongoose .find 查询结果包含查询元数据?不能只是手动投影集合的每个属性,如何只获取文档?
- json - 在javascript中导入json似乎没有成功
- excel - CountIF 计算受条件格式影响的单元格
- c# - 等待被代码忽略并直接通过 Xamarin.Android
- keras - 如何使用 keras 子类 API 在 tensorflow 2.0 中将 BatchNormalization 损失添加到梯度计算中
- akka-http - 在 Akka Http SingleRequest 和 Unmarshaling 中使用 Materializer 是什么?
- go - 从另一个本地包导入本地包
- python - Python - 适合胶合文件的矩阵