如何根据 sql 中的条件给出组号

How to give group numbers based on a condition in sql

这是我的table。我正在使用雪花

CREATE TABLE testx
(
    c_order int,    
    c_condition varchar(10)
);

INSERT INTO testx 
VALUES (1, 'and'), (2, 'and'), (3, 'or'), (4, 'and'), (5, 'or');

SELECT * FROM testx



c_order  c_condition
--------------------
1         and
2         and
3         or
4         and
5         or

我正在尝试编写一个查询,它会根据连续的“and”应该具有相同的组号这一事实为我提供组号。当 'or' 来的时候,应该增加组数。顺便说一句,我们也应该维护c_order。

这是预期的结果:

c_order  c_condition   group_no
-------------------------------
1         and              1
2         and              1
3         or               2
4         and              2
5         or               3

我试过这样使用 dense_rank:

SELECT 
    *, 
    DENSE_RANK() OVER (ORDER BY c_condition) 
FROM testx

但它return 并不是我想要的。有人可以帮忙吗?`

想法是对 C_ORDER 使用与 group_no 相同的值,如果 C_ORDER 比之前的 OR c_order 多。 在 CTE 中,我们只有 select 行带有 OR 并为它们分配一个 使用 ROW_NUMBER() 生成器的组号 -

主查询-

with temp_cte as
(
select c_order,
case -- to check if 'or' is the first row or not
when (select min(c_order) from testx where c_condition='or') = 
(select min(c_order) from testx)
then row_number() over (order by c_order)
else
row_number() over (order by c_order)+1
end rn
from testx, table(generator(rowcount=>1))
where c_condition='or'
)
select x.c_order, x.c_condition,
case
when x.c_order = w.c_order
then w.rn
when x.c_order > (select min(c_order) from temp_cte)
then (select max(rn) from temp_cte where c_order < x.c_order)
else 1
end seq1
from testx x left join temp_cte w
on x.c_order = w.c_order
order by x.c_order;

输出-

C_ORDER C_CONDITION SEQ1
1 and 1
2 and 1
3 or 2
4 or 3
5 and 3
6 and 3
7 or 4
8 and 4
9 or 5

对于data-set

select * from testx;
C_ORDER C_CONDITION
1 and
2 and
3 or
4 or
5 and
6 and
7 or
8 and
9 or