Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a query on a result from another query?

I have a the query:

SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age FROM availables INNER JOIN rooms ON availables.room_id=rooms.id WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate 

Which returns something like:

Date               Age 2009-06-25         0 2009-06-26         2 2009-06-27         1 2009-06-28         0 2009-06-29         0 

How can I then do a Count on the number of rows which is returned.. (in this case 5) and an SUM of the Ages? To return just one row with the Count and the SUM?

Count         SUM 5             3 

Thanks

like image 583
holden Avatar asked Jun 04 '09 09:06

holden


People also ask

How can I use one query result in another query?

Use the results of a query as a field in another query. You can use a subquery as a field alias. Use a subquery as a field alias when you want to use the subquery results as a field in your main query. Note: A subquery that you use as a field alias cannot return more than one field.

How do I create a query for another query in SQL?

A subquery is a query nested inside another query. It can be placed anywhere in a query, even within another subquery. The syntax is very simple – you just put your subquery inside parentheses and insert it into the main query, wherever it is needed.

How do you execute a SQL query only if another SQL query has results?

The common table expression ( WITH clause) wraps the first query that we want to execute no matter what. We then select from the first query, and use UNION ALL to combine the result with the result of the second query, which we're executing only if the first query didn't yield any results (through NOT EXISTS ).


2 Answers

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from (   SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age   FROM availables   INNER JOIN rooms   ON availables.room_id=rooms.id   WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094   GROUP BY availables.bookdate ) AS SUBQUERY 
like image 124
SWeko Avatar answered Sep 23 '22 10:09

SWeko


You just wrap your query in another one:

SELECT COUNT(*), SUM(Age) FROM (     SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age     FROM availables     INNER JOIN rooms     ON availables.room_id=rooms.id     WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094     GROUP BY availables.bookdate ) AS tmp; 
like image 42
soulmerge Avatar answered Sep 21 '22 10:09

soulmerge