Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum totals of two queries

I have two basic queries which I need to sum the totals of:

Select hours, sum(hours) FROM table WHERE name='xxx' and Description='Worked'
Select hours2, sum(hours2) FROM table WHERE name='xxx' and Description2='Worked'

I've tried UNION and it will get me the totals of each query but it will not combine them.

Table setup is:

  • ID
  • name
  • hours
  • description
  • hours2
  • description2

I need to correlate hours to description and hours2 to description2 which is why I have the two different queries. I need to sum the totals of hours and hours2.

like image 340
This Guy Avatar asked Jul 13 '11 20:07

This Guy


1 Answers

First of all, you missed group by, so even though mysql doesn't complain about it, you hours and hours2 values are meaningless. Secondly, you the result of UNION can be put in derived subquery, so you will have the desired total :

SELECT SUM(hr) FROM
(
  Select sum(hours) as hr FROM table WHERE name='xxx' and Description='Worked'
  UNION ALL
  Select sum(hours2) as hr FROM table WHERE name='xxx' and Description2='Worked'
)a
like image 104
a1ex07 Avatar answered Sep 17 '22 19:09

a1ex07