-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrankedcte
60 lines (57 loc) · 1.45 KB
/
rankedcte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
WITH RankedTable AS (
SELECT
id,
priorId,
CASE
WHEN priorId IS NULL THEN 1 -- Highest priority: A, A1
WHEN priorId = id THEN 2 -- Intermediate priority: B
ELSE 3 -- Lowest priority: C, D, ..., N
END AS priority
FROM
your_table
)
SELECT
id,
priorId,
priority,
RANK() OVER (ORDER BY priority, id) AS rank -- Adjusted rank with consistent ordering by id
FROM
RankedTable
ORDER BY
rank, id;
WITH RecursiveHierarchy AS (
-- Base case: Start with all records in the table
SELECT
id,
priorId,
CASE
WHEN priorId IS NULL THEN 1 -- Highest priority
WHEN priorId = id THEN 2 -- Intermediate priority
ELSE 3 -- Lowest priority
END AS priority
FROM
your_table
UNION ALL
-- Recursive step: Include parents of current records
SELECT
p.id,
p.priorId,
CASE
WHEN p.priorId IS NULL THEN 1
WHEN p.priorId = p.id THEN 2
ELSE 3
END AS priority
FROM
your_table p
INNER JOIN RecursiveHierarchy r
ON p.id = r.priorId
)
SELECT DISTINCT
id,
priorId,
priority,
RANK() OVER (ORDER BY priority, id) AS rank
FROM
RecursiveHierarchy
ORDER BY
rank, id;