如何对来自 table 的单个查询执行多个子查询?

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

我有两个表:BUILDINGAPARTMENT.

BUILDING 有 ID_BUILDINGBUILDING_NAME(这就是这个问题唯一重要的)

公寓有 ID_BUILDINGN_APARTMENTSTOTAL_ROOMS

我需要做这样的查询:

| 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                                
|________________________________________________________________________________________________________

卧室的数量可以在 1 到 5 之间。

为此,我提出了 whis 查询:

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;

不幸的是,这计算了所有带 1 个房间的公寓,而不是 BUILDING_NAME:

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

我确实尝试了 here and 的答案,但它们不是同一个问题。

我认为解决方案可能是使用多个连接(或内部连接),但我找不到正确的答案。

提前致谢。

使用条件聚合:

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;