Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何为添加到select的子查询返回多个列?_Sql_Postgresql_Select_Count_Subquery - Fatal编程技术网

Sql 如何为添加到select的子查询返回多个列?

Sql 如何为添加到select的子查询返回多个列?,sql,postgresql,select,count,subquery,Sql,Postgresql,Select,Count,Subquery,我有这样一个问题: select e.field1, e.field2, (select count(field3) from tbl1 where someField = e.field1 group By someType ) as count_1, (select count(field4) from tbl1 where someField = e.field1 group By someType ) as count_2, from ... 我不喜欢代码重复

我有这样一个问题:

select 
   e.field1,
   e.field2,
   (select count(field3) from tbl1 where someField = e.field1 group By someType ) as count_1,
   (select count(field4) from tbl1 where someField = e.field1 group By someType ) as count_2,
from
...
我不喜欢代码重复计数,但如果我做了smth喜欢

select count(field3), count(field3) ....
在子查询中,postgres抱怨子查询必须返回单列


如何修复它?

您可以使用横向连接:

select e.field1,  e.field2, t1.*
from e left join lateral
     (seclect count(tbl1.field3) as count_1, count(tbl1.field4) as count_4
      from tbl1
      where tbl1.someField = e.field1
     ) t1
     on true;
您还可以通过聚合执行此操作:

select e.field1,  e.field2, t1.count_1, t1.count_2
from e left join
     (select tbl1.someField, count(tbl1.field3) as count_1, count(tbl1.field4) as count_2
      from tbl1
      group by tbl1.someField 
     ) t1
     on tbl1.someField = e.field1;

这可能会返回
NULL
值,如果需要,可以使用
coalesce()

将这些值转换为
0
,我需要一个通用查询,该查询对postgres和oracleoracle版本具有相同的语法11@gstackoverflow . . . 第一个解决方案适用于Oracle 12C+和Postgres,考虑到您的问题标签,这似乎是合理的。我添加了一个可以在任何地方使用的替代解决方案。我最初使用这种方法,但性能非常糟糕