计算树结构公司的人数

时间:2018-06-04 20:14:18

标签: sql oracle hierarchical-data recursive-query

您好我有一个结构表,其中包含companies_id(PK)和parent_companies_id(FK)列以及包含companies_id(FK)和people_id(PK)的人员表。有些人可能在不同的公司。想知道包括小孩在内的各公司的数量。

+------------------+-------------------------+
| companies_id(PK) | parent_companies_id(FK) |
+------------------+-------------------------+
|              101 | null                    |
|              102 | 101                     |
|              103 | 101                     |
|              104 | 103                     |
|              105 | 103                     |
|              106 | 104                     |
+------------------+-------------------------+

+---------------+------------------+
| people_id(PK) | companies_id(FK) |
+---------------+------------------+
|           001 |              101 |
|           002 |              102 |
|           003 |              102 |
|           004 |              104 |
|           005 |              105 |
|           006 |              106 |
+---------------+------------------+

CREATE TABLE COMPANY
  ( Company_ID Integer,
    Parent_ID Integer
  );

CREATE TABLE PEOPLE
  ( People_ID VARCHAR(3),
    Company_ID Integer
  );

INSERT INTO COMPANY VALUES (101,NULL);
INSERT INTO COMPANY VALUES (102,101);
INSERT INTO COMPANY VALUES (103,101);
INSERT INTO COMPANY VALUES (104,103);
INSERT INTO COMPANY VALUES (105,103);
INSERT INTO COMPANY VALUES (106,104);

INSERT INTO PEOPLE VALUES ('001',101);
INSERT INTO PEOPLE VALUES ('002',102);
INSERT INTO PEOPLE VALUES ('003',102);
INSERT INTO PEOPLE VALUES ('004',104);
INSERT INTO PEOPLE VALUES ('005',105);
INSERT INTO PEOPLE VALUES ('006',106);

结果必须是下一个

+--------------+------------+
| companies_id | people_qnt |
+--------------+------------+
|          101 |          6 |
|          102 |          2 |
|          103 |          3 |
|          104 |          2 |
|          105 |          1 |
|          106 |          1 |
+--------------+------------+

1 个答案:

答案 0 :(得分:0)

我在这里假设您的var url = 'https://labs.bible.org/api/? passage=random&type=json&callback=myCallBackFcn'; var ourRequest = new XMLHttpRequest(); ourRequest.open('GET', url); ourRequest.onload = function(){ console.log(ourRequest.responseText); }; ourRequest.send(); 表(我称之为#34; struct")对每家公司都有一行。如果这不是真的,你应该为驾驶表使用不同的东西。

structure

Sqlfiddle