我有以下表结构,它是根据从 UI 中的选择生成的,并按照从 UI 生成的方式存储。这基本上是存储查询序列。
例如
(( Condition AND Condition) OR ( Condition ))
Id ConditionType Value Brackets 1 NULL NULL ( 2 NULL NULL ( 3 NULL Condition NULL 4 AND NULL NULL 5 NULL Condition NULL 6 NULL NULL ) 7 OR NULL NULL 8 NULL NULL ( 9 NULL Condition NULL 10 NULL NULL ) 11 NULL NULL )
根据以上信息,我需要生成一个索引:
Id StartIndex EndIndex 1 1 11 2 2 6 3 8 10
关于如何做到这一点有什么想法吗?
最佳答案
编辑:在第 1 版中,我没有考虑嵌套级别。这个我测试过:)
我在 DB2 上工作,所以如果它不支持 LATERAL 连接,您可能必须为 sql-server 重构它,但是这个使用您在 DB2 上的值集产生了正确的结果:
with CTE_ONLY_BRACKETS as (
select *
from MYLIST
where Brackets in('(',')')
) ,
CTE_NEST_INCREMENT as (
select Id
,Brackets
,case when Brackets = '(' then 1 else -1 end as NEST_INCREMENT
from CTE_ONLY_BRACKETS
) ,
CTE_NEST_LEVEL as (
select Id
,Brackets
,S.NEST_LEVEL
from CTE_NEST_INCREMENT C
cross join lateral (
select sum( NEST_INCREMENT ) as NEST_LEVEL
from CTE_NEST_INCREMENT S
where S.Id <= C.Id
) as S
)
select row_number() over() as Id
,L.Id as StartIndex
,R.Id as EndIndex
from CTE_NEST_LEVEL R
cross join lateral (
select L.Id
from CTE_NEST_LEVEL L
where L.Brackets = '('
and L.Id < R.Id
and L.NEST_LEVEL = R.NEST_LEVEL + 1
order by L.Id desc
fetch first row only
) as L
where R.Brackets = ')'
order by L.Id
关于sql - 从 SQL 中的表中顺序读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26942929/