tags:

views:

58

answers:

3

I have three SQL selects, the results of which I need to add together. Two of the three use fairly complex joins.

select sum(field_one) from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=:id
select sum(field_two) from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=:id
select sum(field_three) from t_e where t_e.user_id=:id

What I need is the sum of all three values. sum(field_one)+sum(field_two)+sum(field_three). Is there anyway to do this in a single statement?

+2  A: 

You can use a UNION and a subselect to do that:

select sum(`sum`) FROM
(
  select sum(field_one) as `sum` from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=:id
  UNION ALL
  select sum(field_two) from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=:id
  UNION ALL
  select sum(field_three) from t_e where t_e.user_id=:id
) as x;

Edit: Updated my answer to use UNION ALL, as suggested by Peter Lang.

Dennis Haarbrink
+5  A: 

You could UNION ALL them.
Do not use UNION, since it omits duplicate values (5+5+5 would result in 5).

Select Sum(s)
From
(
  Select Sum(field_one) As s ...
  Union All
  Select Sum(field_two) ...
  Union All
  Select Sum(field_three) ...
) x
Peter Lang
+1 and good thinking on the `UNION ALL`
Brendan Bullen
+4  A: 

You can do this without using Union like this

Sample Query

select( (select 15) + (select 10) + (select 20)) 

Your Query

select
(
    (select sum(field_one) from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=:id) +
    (select sum(field_two) from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=:id) +
    (select sum(field_three) from t_e where t_e.user_id=:id) 
)
Aamod Thakur
`+1`: Should work for MySQL and SQL-Server, not Oracle though, but that was not the question :)
Peter Lang
I dont know oracle anyways neither do i know MySQL :P May be i must try to learn it in near future
Aamod Thakur