SQL 返回所有行和计数
SQL returning all rows and count
我有 3 个表,属性 个经理、地址和单位。我正在尝试使用聚合函数 COUNT 获取所有行,但它只有 returns 1 行。
我想获取 pmNo = 1 的所有地址以及每个地址的单元总数。我的 SQl 查询是这样的:
SELECT a.*, COUNT(u.unitId) AS totalUnits
FROM Units AS u
JOIN Addresses AS a ON a.addressNo = u.addressNo
JOIN PropertyManagers AS pm ON pm.pmNo = a.pmNo
WHERE pm.pmNo = 1
这给了我以下结果:
addressNo city province postalCode buildingName pmNo totalUnits
1 city1 prov1 V9F3b6 building1 Apt. 1 3
这是对的,但它只给了我第一个地址字段,然后将两个地址单元组合成总单元。
我想要的结果是:
addressNo city province postalCode buildingName pmNo totalUnits
1 city1 prov1 V9F3b6 building1 Apt. 1 2
2 city2 prov2 V0N1U8 building2 Apt. 1 1
COUNT
等 non-simple 案例的聚合函数需要指定发生的聚合。在您的情况下,您需要地址。由于 addressNo
是主键和唯一地址的最简单标识符,因此使用查询的 GROUP BY
:
SELECT a.*, COUNT(u.unitId) AS totalUnits
FROM Units AS u
JOIN Addresses AS a ON a.addressNo = u.addressNo
JOIN PropertyManagers AS pm ON pm.pmNo = a.pmNo
WHERE pm.pmNo = 1
GROUP BY a.addressNo
我有 3 个表,属性 个经理、地址和单位。我正在尝试使用聚合函数 COUNT 获取所有行,但它只有 returns 1 行。
我想获取 pmNo = 1 的所有地址以及每个地址的单元总数。我的 SQl 查询是这样的:
SELECT a.*, COUNT(u.unitId) AS totalUnits
FROM Units AS u
JOIN Addresses AS a ON a.addressNo = u.addressNo
JOIN PropertyManagers AS pm ON pm.pmNo = a.pmNo
WHERE pm.pmNo = 1
这给了我以下结果:
addressNo city province postalCode buildingName pmNo totalUnits
1 city1 prov1 V9F3b6 building1 Apt. 1 3
这是对的,但它只给了我第一个地址字段,然后将两个地址单元组合成总单元。
我想要的结果是:
addressNo city province postalCode buildingName pmNo totalUnits
1 city1 prov1 V9F3b6 building1 Apt. 1 2
2 city2 prov2 V0N1U8 building2 Apt. 1 1
COUNT
等 non-simple 案例的聚合函数需要指定发生的聚合。在您的情况下,您需要地址。由于 addressNo
是主键和唯一地址的最简单标识符,因此使用查询的 GROUP BY
:
SELECT a.*, COUNT(u.unitId) AS totalUnits
FROM Units AS u
JOIN Addresses AS a ON a.addressNo = u.addressNo
JOIN PropertyManagers AS pm ON pm.pmNo = a.pmNo
WHERE pm.pmNo = 1
GROUP BY a.addressNo