我有以下表格:
人:
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;
但它没有像我期望的那样工作。
非常感谢任何帮助。
答案 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