I currently have two select commands as per below. What I would like to do is to add the results together in the SQL query rather than the variables in code.
select sum(hours) from resource; select sum(hours) from projects-time;
Is it possible to have both in the same SQL and output a sum of both results?
The UNION operator is used to combine the data from the result of two or more SELECT command queries into a single distinct result set.
The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It does not remove duplicate rows between the various SELECT statements (all rows are returned). Each SELECT statement within the UNION ALL must have the same number of fields in the result sets with similar data types.
You need to create two separate queries and join their result not JOIN their tables. Show activity on this post. JOIN and UNION are differents. In your query you have used a CROSS JOIN operation, because when you use a comma between two table you apply a CROSS JOIN.
Yes. It is possible :D
SELECT SUM(totalHours) totalHours FROM ( select sum(hours) totalHours from resource UNION ALL select sum(hours) totalHours from projects-time ) s
As a sidenote, the tablename projects-time
must be delimited to avoid syntax error. Delimiter symbols vary on RDBMS you are using.
Something simple like this can be done using subqueries in the select
clause:
select ((select sum(hours) from resource) + (select sum(hours) from projects-time) ) as totalHours
For such a simple query as this, such a subselect is reasonable.
In some databases, you might have to add from dual
for the query to compile.
If you want to output each individually:
select (select sum(hours) from resource) as ResourceHours, (select sum(hours) from projects-time) as ProjectHours
If you want both and the sum, a subquery is handy:
select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours from (select (select sum(hours) from resource) as ResourceHours, (select sum(hours) from projects-time) as ProjectHours ) t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With