首页 > 解决方案 > 如何在 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

如何解决。

提前致谢。

标签: sqldb2subquery

解决方案


为什么你在子查询中引用同一个表,我猜你可以简单地使用 CASE 语句 -

 SELECT grp1,
        COUNT(DISTINCT CASE WHEN lamp = 1 THEN tt.comp END) AS COMP
FROM (select ......) as t
GROUP BY grp1

推荐阅读