Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Combine Multiple SQL Queries?

Tags:

sql

I'm having some trouble figuring out any way to combine two SQL queries into a single one that expresses some greater idea.

For example, let's say that I have query A, and query B. Query A returns the total number of hours worked. Query B returns the total number of hours that were available for workers to work. Each one of these queries returns a single column with a single row.

What I really want, though, is essentially query A over query B. I want to know the percentage of capacity that was worked.

I know how to write query A and B independently, but my problem comes when I try to figure out how to use those prewritten queries to come up with a new SQL query that uses them together. I know that, on a higher level, like say in a report, I could just call both queries and then divide them, but I'd rather encompass it all into a single SQL query.

What I'm looking for is a general idea on how to combine these queries using SQL.

Thanks!

like image 358
Jazzepi Avatar asked Dec 14 '10 16:12

Jazzepi


People also ask

How do I use multiple SQL statements?

To submit multiple SQL statements in a single request: In the statement field, use a semicolon ( ; ) between each statement. In the parameters field, set the MULTI_STATEMENT_COUNT field to the number of SQL statements in the request.

Which query is used to combine records from multiple tables?

Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. USING (id);

How do I merge two MySQL queries?

The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.


1 Answers

Unconstrained JOIN, Cartesian Product of 1 row by 1 row

SELECT worked/available AS PercentageCapacity
FROM ( SELECT worked FROM A ), 
     ( SELECT available FROM B )
like image 178
kevpie Avatar answered Oct 02 '22 20:10

kevpie