为什么SQL子查询在SUM函数中不起作用?

问题描述

我正在学习SQL,本课是子查询。我的查询是:

select sum (select tientra from thang7_8714 where tientra > 0) as tmp;

但是Postgres注意到了我的消息:

ERROR:  syntax error at or near "select" LINE 1: select sum (select
  tientra from thang7_8714 where tientra > ...
  SQL state: 42601 Character: 13

我知道我可以在不使用子查询的情况下获得结果,但是我正在尝试使用它,因此我在SUM函数中使用了子查询,但是无法使用。

请帮助我理解SQL子查询。

解决方法

通常,SQL不允许聚合函数具有作为子查询的参数。通用解决方案是将聚合移入子查询:

select (select sum(tientra) from thang7_8714 where tientra > 0) as tmp;

大概,您知道解决这个问题的更规范的方法是:

select sum(tientra) as tmp
from thang7_8714
where tientra > 0;
,

带有子查询的总和

SUM需要一个参数。它可以是固定值(例如123)或列(例如mycolumn)或表达式(例如123 * mycolumn)或子查询。但是此子查询必须是标量的,这意味着它仅返回一个值。

子查询用括号括起来,因此带有子查询的SUM看起来像这样:

select sum( (select t2.value from t2 where t2.id = t1.id_t1) )
from t1;

但是聚合函数中的子查询非常少见,因为我们可以通过联接(例如select sum(t2.value) from t1 join t2 on t2.id = t1.id_t2;)来实现相同的目的。

子查询的典型位置:

SELECT

select col1,col2,(<scalar subquery>) from ...

如果需要,子查询在这里必须是标量。

FROM

select t.col1,sq.col2 from t join (<subquery>) sq on ...

此处子查询通常是聚合查询,例如

select a.x,bagg.total
from a 
join 
(
  select y,sum(value) as total
  from b
  group by y
) bagg on bagg.y = a.x;

IN /存在

select * from t join where colx in (<subquery>);

EXISTS子查询通常与主查询相关联,即引用主查询中的列:

select * from a join where exists (select * from b where b.x = a.y);

通常IN子句不相关:

select * from a join where a.y in (select b.x from b);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...