SQL查询中的COUNT()的SUM()

时间:2014-10-05 11:00:31

标签: sql count group-by sum aggregate-functions

我有以下表格:

PersonID(PK)
AppartmentID(FK)
Name

Appartments公寓

AppartmentID(PK)
BuildingID(FK)
ApartmentNumber

建筑物

BuildingID
Address

我想知道每栋楼里有多少人居住,就像那样:

| Address  | Sum |
|----------|-----|
| Address1 | 169 |
| Address2 | 353 |
| Address3 | 232 |
| Address4 | 199 |

到目前为止,我得到的最佳查询是:

SELECT 
   Buildings.BuildingID,
   sum(c)
FROM
   (SELECT 
        COUNT(*) as c 
    FROM 
        Persons
    GROUP BY 
        Persons.AppartmentID) as c, Appartments
GROUP BY 
    Buildings.BuildingID;

但它没有像我期望的那样工作。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

SELECT b.BuildingID, 
       b.Address, 
       count(p.personID) as persons
FROM Buildings b
LEFT JOIN Appartments a ON a.BuildingID = b.BuildingID
INNER JOIN Persons p ON p.AppartmentID = a.AppartmentID
GROUP BY b.BuildingID, b.Address