[用正确的数据和我用来获取输出的代码重新发布问题]
我有一个存储表,其中包含storeid、isactive 和transferstoreid。 id=店铺id isactive= 商店(id 列)是否处于活动状态 Transferstoreid = 如果 isactive=0,则先前商店将转移到的新商店 ID
我想识别所有商店及其活跃的父母。如果存储处于活动状态,即 1,则 Transferstoreid 为 NULL,并且 id 将直接是父级。 然而,可能存在这样的情况:商店 1 转移到商店 2,然后商店 2 转移到商店 3,直到 .....n。
如何获取所有商店及其当前活跃的转移商店(或父商店)的列表
例如,如果商店 10 关闭(isactive=0)并转移到商店 14,但随后 14 关闭(isactive=0)并转移到 20,然后 20 也关闭(isactive=0)并转移到 25 (有效=1);因此,对于商店 10,14,20 -> 父/活动商店将为 25,对于商店 25,父商店本身将为 25(id)
这是示例数据:
-- Create the store table
CREATE TABLE store (
ID INT,
ISACTIVE INT,
TRANSFERTONEXTSTOREID INT
);
-- Insert data into the store table
INSERT INTO store (ID, ISACTIVE, TRANSFERTONEXTSTOREID)
VALUES
(54, 0, 77),
(101, 0, 120),
(10, 0, 14),
(77, 1, NULL),
(40, 0, 99),
(99, 0, 101),
(12, 1, NULL),
(37, 0, 54),
(20, 0, 25),
(60, 1, NULL),
(38, 1, NULL),
(120, 1, NULL),
(14, 0, 20),
(25, 1, NULL),
(11, 0, 12);
我可以轻松地通过分层查询(通过根和路径连接)来做到这一点。我在 Oracle Apex 中使用过这个查询
SELECT CONNECT_BY_ROOT ID AS store_id, id as current_id
FROM store
WHERE ISACTIVE = 1
CONNECT BY PRIOR TRANSFERTONEXTSTOREID = ID;
并得到这个输出:
STORE_ID CURRENT_ID
10 25
11 12
12 12
14 25
20 25
25 25
37 77
38 38
40 120
54 77
60 60
77 77
99 120
101 120
120 120
如何在 SQL Server 中执行此操作
任何线索将不胜感激。
参见示例
with rec_cte AS (
select s.id, s.id as current_id,
s.isactive,
1 as reclevel
FROM store s
where isactive=1
UNION ALL
select s.id, r.current_id as current_id,
s.isactive,
r.reclevel + 1
FROM rec_cte r
JOIN store s ON s.transfertonextstoreid = r.id
)
select * from rec_cte
order by id,reclevel;