如何在 sql 服务器中创建结合两列的关系有序数据?
How can I create relational ordered data combining two columns in sql server?
我想使用层次逻辑根据它们的顺序关系将同一 table 中的两个关系列合并为一个列。每行包含 currentstate
和 nextstate
。并且这两列有关于排序的关系。
为了说明;
id currentstate nextstate
1 1 2
2 4 5
3 2 3
4 3 4
5 5 6
6 6 9
7 9 15
8 15 15
应用正确解决方案时的预期结果;
stateflow
1
2
3
4
5
6
9
15
我应该遵循哪种方法来获得这个结果?
您想使用递归 cte。像这样:
with cte as (
select currentstate, nextstate, 1 as ord
from t
where not exists (select 1 from t t2 where t2.nextstate = t.currentstate)
union all
select cte.currentstate, t.nextstate, ord + 1
from cte join
t
on cte.nextstate = t.currentstate
where t.nextstate <> t.currentstate
)
select *
from cte
order by ord;
注意:这假设没有循环,并根据从源节点到最终节点的最短路径分配顺序。
删除循环需要 where
子句。
这是基于戈登回答的查询
with cte as (
select currentstate, nextstate, 1 as ord
from table1
where currentstate = (SELECT MIN(currentstate) FROM table1)
union all
select t.currentstate, t.nextstate, ord + 1
from cte
inner join table1 t
on cte.nextstate = t.currentstate
where cte.nextstate <> cte.currentstate
)
select currentstate AS stateflow
from cte
order by ord
OPTION (MAXRECURSION 0);
我想使用层次逻辑根据它们的顺序关系将同一 table 中的两个关系列合并为一个列。每行包含 currentstate
和 nextstate
。并且这两列有关于排序的关系。
为了说明;
id currentstate nextstate
1 1 2
2 4 5
3 2 3
4 3 4
5 5 6
6 6 9
7 9 15
8 15 15
应用正确解决方案时的预期结果;
stateflow
1
2
3
4
5
6
9
15
我应该遵循哪种方法来获得这个结果?
您想使用递归 cte。像这样:
with cte as (
select currentstate, nextstate, 1 as ord
from t
where not exists (select 1 from t t2 where t2.nextstate = t.currentstate)
union all
select cte.currentstate, t.nextstate, ord + 1
from cte join
t
on cte.nextstate = t.currentstate
where t.nextstate <> t.currentstate
)
select *
from cte
order by ord;
注意:这假设没有循环,并根据从源节点到最终节点的最短路径分配顺序。
删除循环需要 where
子句。
这是基于戈登回答的查询
with cte as (
select currentstate, nextstate, 1 as ord
from table1
where currentstate = (SELECT MIN(currentstate) FROM table1)
union all
select t.currentstate, t.nextstate, ord + 1
from cte
inner join table1 t
on cte.nextstate = t.currentstate
where cte.nextstate <> cte.currentstate
)
select currentstate AS stateflow
from cte
order by ord
OPTION (MAXRECURSION 0);