Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SUM() multiple subquery rows in MySQL?

Tags:

mysql

The question is simple: I want to do:

SELECT SUM((... a subquery that returns multiple rows with a single int value ...)) 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.

like image 796
Tower Avatar asked Sep 24 '10 09:09

Tower


1 Answers

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;
like image 150
Ike Walker Avatar answered Sep 21 '22 06:09

Ike Walker