如何在 MySQL 中 SUM() 多个子查询行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3785600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:14:59  来源:igfitidea点击:

How to SUM() multiple subquery rows in MySQL?

mysql

提问by Tower

The question is simple: I want to do:

问题很简单:我想做:

SELECT SUM((... a subquery that returns multiple rows with a single int value ...)) AS total;

SELECT SUM((...一个子查询,返回多行和一个int值...)) AS total;

How would I do that? I get an error saying that subquery returns more than one row. I need to have it in a subquery.

我该怎么做?我收到一条错误消息,说子查询返回多于一行。我需要在子查询中使用它。

回答by Ike Walker

Here's an approach that should work for you:

这是一种应该适合您的方法:

SELECT SUM(column_alias)
FROM (select ... as column_alias from ...) as table_alias

And here's a specific dummy example to show the approach in action:

这是一个特定的虚拟示例,用于展示该方法的实际应用:

select sum(int_val) 
from (
  select 1 as int_val 
  union
  select 2 as int_val 
  union 
  select 3 as int_val
) as sub;

回答by jensgram

Couldn't you just do the aggregation withinthe subquery?

你不能只子查询中进行聚合吗?

SELECT
    (SELECT SUM(...) ...) AS total,
    ...

(Untested!)

(未经测试!)