Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add results of two select commands in same query

Tags:

sql

select

sqlite

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?

like image 720
Rhys Avatar asked Mar 01 '13 03:03

Rhys


People also ask

Is used to combine the results of two or more SELECT statements?

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.

How can you combine and return the result set retrieved by two or more SELECT?

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.

How do I combine two SQL queries in one result without a UNION?

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.


2 Answers

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.

like image 70
John Woo Avatar answered Oct 09 '22 08:10

John Woo


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 
like image 28
Gordon Linoff Avatar answered Oct 09 '22 08:10

Gordon Linoff