You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何COUNT函数可正常运行,SUM函数执行却报错?

解决SUM函数替换COUNT后的SQL语法错误问题

错误原因

你遇到的语法错误是因为**SUM(*)是非法写法**:

  • COUNT(*)用于统计结果集的总行数,因此可以用*指代所有列;
  • SUM()函数必须接收一个具体的数值列作为参数,用来计算该列所有值的总和,不能直接使用*。

正确写法示例

方法1:合并多表后求和(保留原查询结构)

如果需要保留UNION的结构,要明确指定求和的列(此处为s);同时建议用UNION ALL替代UNION(避免不必要的去重操作,提升查询效率,若业务需要去重则保留UNION):

create table t1(s int);
create table t2(s int);
create table t3(s int);

insert into t1 values(1);
insert into t2 values(2);
insert into t3 values(3);

select sum(s) from 
(select s from t1 union all 
 select s from t2 union all 
 select s from t3
) as ta;

方法2:分别求和后相加(性能更优)

无需合并表,直接对每个表单独求和再累加,这种方式避免了子查询和数据合并,执行效率更高:

select 
  (select sum(s) from t1) +
  (select sum(s) from t2) +
  (select sum(s) from t3) as total_sum;

内容的提问来源于stack exchange,提问作者JMP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:02:20