通过与下一行比较选择行

时间:2019-05-31 16:39:38

标签: sql oracle

我有下表

value   caseid    version
-----   ------    -------
2.6     1         A
2.7     1         B
4.8     2         A
5.4     2         B
2.9     3         A
3.0     3         B

,我想比较版本为value的行中的A和具有相同的B的版本caseid的行,并且只显示差异为大于0.1。

因此,在上面的示例中,结果应为:

value   caseid    version
-----   ------    -------
4.8     2         A
5.4     2         B

我尝试了联接,但是随后两行都显示在同一行中。 有没有一种方法可以使值显示在不同的行上?

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用lag()窗口分析功能:

with t1( value, caseid, version ) as
(
 select 2.6, 1, 'A' from dual union all
 select 2.7, 1, 'B' from dual union all
 select 4.8, 2, 'A' from dual union all
 select 5.4, 2, 'B' from dual union all
 select 2.9, 3, 'A' from dual union all
 select 3.0, 3, 'B' from dual 
), t2 as
(
select t1.value - lag(t1.value,1,t1.value) over 
       (partition by t1.caseid order by t1.version ) as diff,
       t1.* 
  from t1
)
select value, caseid, version
  from t2
 where t2.caseid in ( select caseid 
                        from t2 
                       where caseid = t2.caseid 
                         and diff > .1 )
 order by version;

VALUE   CASEID  VERSION
-----   ------  -------
4,80    2       A
5,40    2       B

Demo

答案 1 :(得分:0)

您可以使用union all


with tab as(
select 2.6 as value,     1  as caseid,       'A' as version from dual union all
select 2.7,     1,         'B' from dual union all
select 4.8,     2,         'A' from dual union all
select 5.4,     2,         'B' from dual union all
select 2.9,     3,         'A' from dual union all
select 3.0,     3,         'B' from dual 
)

select t1.value, t1.caseid, t1.version
  from tab t1
  join tab t2 on t1.caseid = t2.caseid
  where (t1.value- t2.value) > 0.1
union all
select t2.value, t2.caseid, t2.version
  from tab t1
  join tab t2 on t1.caseid = t2.caseid
  where (t1.value- t2.value) > 0.1

db <>提琴here