[英]Why SQL subquery doesn't work inside SUM function?
我正在学习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
function 中使用子查询但不能。
请帮助我理解 SQL 子查询。
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 col1, col2, (<scalar subquery>) 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;
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);
通常,SQL 不允许聚合函数具有作为子查询的 arguments。 通用解决方案是在子查询中移动聚合:
select (select sum(tientra) from thang7_8714 where tientra > 0) as tmp;
据推测,您知道解决这个问题的更规范的方法是:
select sum(tientra) as tmp
from thang7_8714
where tientra > 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.