[英]How to find levels in a hierarchy by dates using SQLite
如何使用帶有遞歸表達式的 SQLite 按日期為層次結構中的每個人查找級別。
我發現以下 帖子詳細介紹了使用遞歸查詢對 SQLite 中的分層數據進行計算,以及StackOverflow 上的一篇文章,用於 SQLite3 上的基本遞歸查詢。
現在,在 SQLite 的文檔中有一個很好的詳細示例,關於如何從單個員工的角度處理分層數據的計算(第 3.2 部分的示例)。
好吧,到目前為止,我知道如何計算選定個人的級別(哇哦),但我無法彌合差距並使此查詢按日期應用於所有個人。
這是我為 1 個人完成這項工作的部分查詢:
WITH RECURSIVE supervisor_of(id, boss_id, date_interest) AS (
SELECT org_1.id, org_1.boss_id, org_1.date_interest
FROM org org_1
WHERE id = 4 -- Here is the input for the individual
UNION
SELECT org_1.id, org_1.boss_id, org_1.date_interest
FROM org org_1
JOIN supervisor_of so
ON so.boss_id = org_1.id
AND so.date_interest = org_1.date_interest
)
SELECT *,
COUNT(id) AS level
FROM supervisor_of
GROUP BY date_interest
ORDER BY date_interest
和 output:
| id | boss_id | date_interest | level |
| ---- | ------- | ------------- | ----- |
| 4 | 2 | 2 | 3 |
| 4 | 2 | 3 | 3 |
但我無法設法繞過我的頭來得到這個結果:
| id | boss_id | date_interest | level |
| ---- | ------- | ------------- | ----- |
| 1 | | 1 | 1 |
| 2 | 1 | 1 | 2 |
| 3 | 1 | 1 | 2 |
| 1 | | 2 | 1 |
| 2 | 1 | 2 | 2 |
| 3 | 1 | 2 | 2 |
| 4 | 2 | 2 | 3 |
| 1 | | 3 | 1 |
| 2 | 1 | 3 | 2 |
| 3 | 1 | 3 | 2 |
| 4 | 2 | 3 | 3 |
| 5 | 4 | 3 | 4 |
以下是如何加載數據以進行此測試:
CREATE TABLE org(
id TEXT,
boss_id TEXT,
date_interest TEXT
);
-- 1st Date
INSERT INTO org (id, boss_id, date_interest) VALUES(1, NULL, 1);
INSERT INTO org (id, boss_id, date_interest) VALUES(2, 1, 1);
INSERT INTO org (id, boss_id, date_interest) VALUES(3, 1, 1);
-- 2nd Date
INSERT INTO org (id, boss_id, date_interest) VALUES(1, NULL, 2);
INSERT INTO org (id, boss_id, date_interest) VALUES(2, 1, 2);
INSERT INTO org (id, boss_id, date_interest) VALUES(3, 1, 2);
INSERT INTO org (id, boss_id, date_interest) VALUES(4, 2, 2);
-- 3rd Date
INSERT INTO org (id, boss_id, date_interest) VALUES(1, NULL, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(2, 1, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(3, 1, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(4, 2, 3);
INSERT INTO org (id, boss_id, date_interest) VALUES(5, 4, 3);
從代碼中刪除WHERE
子句,以便查詢所有id
以及遞歸CTE
select supervisor_of.id
而不是org_1.id
的第二部分。
最后,您還必須按id
分組:
WITH RECURSIVE supervisor_of(id, boss_id, date_interest) AS (
SELECT org_1.id, org_1.boss_id, org_1.date_interest
FROM org org_1
UNION
SELECT so.id, org_1.boss_id, org_1.date_interest
FROM org org_1 JOIN supervisor_of so
ON so.boss_id = org_1.id AND so.date_interest = org_1.date_interest
)
SELECT *, COUNT(*) AS level
FROM supervisor_of
GROUP BY date_interest, id
ORDER BY date_interest, id
請參閱演示。
結果:
ID | boss_id | 日期興趣 | 等級 |
---|---|---|---|
1 | null | 1 | 1 |
2 | 1 | 1 | 2 |
3 | 1 | 1 | 2 |
1 | null | 2 | 1 |
2 | 1 | 2 | 2 |
3 | 1 | 2 | 2 |
4 | 2 | 2 | 3 |
1 | null | 3 | 1 |
2 | 1 | 3 | 2 |
3 | 1 | 3 | 2 |
4 | 2 | 3 | 3 |
5 | 4 | 3 | 4 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.