让我尝试解释一下我想如何处理我的数据。我的数据结构如下:
我有 3 列:date
、id
和 stage
。阶段可以是不同的数字,但我有兴趣显示某些 id 从 stage
-1
到 stage
1< 的特定转换
。请参阅下面的示例。
我有一个
id
位于stage
-1
,然后转换到 stage1
,稍后又回到阶段-1
。每当从-1
转换到1
时,我都需要那个id
。在这里,我从
-1
过渡到3
,但这不是我感兴趣的。这里,转换完成了,这个
id
就是我想要显示的内容。在这里,我们从
1
转换到-1
,但这不是我想要的。
数据:
#1 date id stage
2018-12-31 520000000001354292 -1
2019-09-30 520000000001354292 1
2019-12-31 520000000001354292 -1
#2 2018-12-31 520000000001435675 -1
2019-03-31 520000000001435675 -1
2019-06-30 520000000001435675 3
#3 2018-12-31 520000000003156164 -1
2019-03-31 520000000003156164 -1
2018-12-31 520000000003161014 -1
2019-03-31 520000000003161014 1
#4 2018-12-31 520500000002472437 1
2019-03-31 520500000002472437 -1
2019-06-30 520500000002472437 -1
2019-09-30 520500000002472437 2
我想要的输出是:
520000000001354292
520000000003156164
我希望我已经解释得足够清楚了。
此外,在此之后,我想显示从 -1
和 1
到 stage
3
的过渡.
最佳答案
您可以使用lag()
:
select distinct id
from (
select t.*, lag(stage) over(partition by id order by date) lag_stage
from mytable t
) t
where lag_stage = -1 and stage = 1
这将带来至少一次从 -1
到 1
转换的所有 id
。
Also, after this, i want to show transition from either -1 and 1 to stage 3.
您也可以轻松调整查询以适应该用例。只需将最后的 where
子句更改为:
where lag_stage in (-1, 1) and stage = 3
关于SQL Informix 高级查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64589000/