Search code examples
oraclecorrelated-subquery

How can I do multiples sub-querys on a single query from one table?


I've got two tables: BUILDING and APARTMENT.

BUILDING has ID_BUILDING, BUILDING_NAME (and that's what only matter for this question)

APARTMENT has ID_BUILDING, N_APARTMENTS, TOTAL_ROOMS.

I need to do a query like this:

| BUILDING NAME | TOTAL APARTMENTS | TOTAL APARTMENTS WITH 1 BEDROOM | TOTAL APARTMENTS WITH 2 BEDROOMS |
|---------------|------------------|---------------------------------|----------------------------------|
| BUILDING A    | 31               | 8                               | 0                                 
|_______________________________________________________________________________________________________|
| BUILDING B    | 20               | 14                              | 11                               
|________________________________________________________________________________________________________
| BUILDING C    | 41               | 90                              | 5                                
|________________________________________________________________________________________________________

The amount of bedroom can be in between 1 and 5.

For that I've come with whis query:

SELECT E.BUILDING_NAME as "name", COUNT(D.N_APARTMENTS) "TOTAL APARTMENTS", (SELECT COUNT(D1.TOTAL_ROOMS) FROM APARTMENT D1 WHERE D1.TOTAL_ROOMS = 1)
FROM BUILDING E
JOIN APARTMENT D 
ON E.ID_BUILDING = D.ID_BUILDING    
GROUP BY E.E.BUILDING_NAME
ORDER BY E.BUILDING_NAME;

Unfortunately, that counts all apartments with 1 room, not by BUILDING_NAME:

| BUILDING NAME | TOTAL APARTMENTS | TOTAL APARTMENTS WITH 1 BEDROOM |
|---------------|------------------|---------------------------------|
| BUILDING A    | 31               | 122                             |
| BUILDING B    | 20               | 122                             |
| BUILDING C    | 41               | 122                             |

I did try the answers here and here but they are not quite the same problem.

I think the solution might be using multiple joins (or inner joins) but I can't find the right answer.

Thanks in advance.


Solution

  • Using conditional aggregation:

    SELECT E.BUILDING_NAME as "name", 
     COUNT(D.N_APARTMENTS) "TOTAL APARTMENTS", 
     SUM(CASE WHEN D.TOTAL_ROOMS = 1 THEN 1 ELSE 0 END) AS "TOTAL APARTMENTS WITH 1 BEDROOM"
    FROM BUILDING E
    JOIN APARTMENT D 
    ON E.ID_BUILDING = D.ID_BUILDING    
    GROUP BY E.E.BUILDING_NAME
    ORDER BY E.BUILDING_NAME;