我有两张table,位置和地址。地方包括像亲子层次的地方。地址包括带有place\u id列的地址。这些表格如下所示;
PLACE
ID PARENT_ID NAME CONTINENT
11 null USA America
22 11 New York America
33 22 Manhattan America
44 null Brasil America
55 44 Rio America
66 null France Europe
77 66 Paris Europe
88 66 Nice Europe
MEMBER
ID PLACE_ID NAME ADRESS
1 22 .. ..
2 77 .. ..
3 33 .. ..
4 22 .. ..
5 55 .. ..
6 55 .. ..
7 88 .. ..
8 88 .. ..
9 88 .. ..
10 22 .. ..
Expected Result:
ID PARENT_ID MEMBER_COUNT PLACE_NAME CONTITNET
11 null 4 USA America
22 11 4 New York America
33 22 1 Manhattan America
44 null 2 Brasil America
55 44 2 Rio America
66 null 4 France Europe
77 66 1 Paris Europe
88 66 3 Nice Europe
我想知道在哪个地方有多少会员。我无法将子位置的成员计数添加到父位置。我的查询如下所示;
WITH MEMBER_COUNT_BY_PLACE AS (
SELECT P.PLACE_ID, COUNT(P.ID) AS MEMBER_COUNT
FROM MEMBER P
GROUP BY P.PLACE_ID
) SELECT C.ID, C.NAME, C.PARENT_ID AS PARENTID, C.CONTINENT, SUM(NVL(D.MEMBER_COUNT, 0)) AS MEMBER_COUNT
FROM PLACE C LEFT JOIN MEMBER_COUNT_BY_PLACE D ON D.PLACE_ID = C.ID
START WITH D.PLACE_ID IS NOT NULL
CONNECT BY PRIOR C.PARENT_ID = C.ID
GROUP BY C.ID, C.NAME, C.PARENT_ID, C.CONTINENT
ORDER BY CONTINENT ASC, PARENT_ID ASC NULLS FIRST;
谢谢你的帮助。
2条答案
按热度按时间jfgube3f1#
这里有一个选择:
首先是样本数据:
然后,一些CTE(见注解):
结果是:
guicsvcw2#
此查询还聚合子成员:
完整示例:
结果: