Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select "step" records

Tags:

sql

postgresql

Given the following table

  grp |   ind |   val
----------------------
    a |     1 |     1
    a |     2 |     1
    a |     3 |     1
    a |     4 |     2
    a |     5 |     2
    a |     6 |     4
    a |     7 |     2
    b |     1 |     1
    b |     2 |     1
    b |     3 |     1
    b |     4 |     3
    b |     5 |     3
    b |     6 |     4

I need to select the following:

  grp |   ind |   val
----------------------
    a |     1 |     1
    a |     4 |     2
    a |     6 |     4
    a |     7 |     2
    b |     1 |     1
    b |     4 |     3
    b |     6 |     4

That is for each 'grp', each record where the 'val' is different to the proceeding 'val' (ordered by 'index') So each record where the 'value' "steps".

what would be the most efficient way to achieve this?

thanks.

Here is a script to create the test case:

create temp table test_table
(
    grp character varying,
    ind numeric,
    val numeric
);
insert into test_table values
    ('a', 1 , 1),
    ('a', 2 , 1),
    ('a', 3 , 1),
    ('a', 4 , 2),
    ('a', 5 , 2),
    ('a', 6 , 4),
    ('a', 7 , 2),
    ('b', 1 , 1),
    ('b', 2 , 1),
    ('b', 3 , 1),
    ('b', 4 , 3),
    ('b', 5 , 3),
    ('b', 6 , 4);
like image 945
pstanton Avatar asked Jun 06 '26 13:06

pstanton


1 Answers

select grp,
       ind,
       val
from (
   select grp, 
          ind, 
          val,
          lag(val,1,0::numeric) over (partition by grp order by ind) - val as diff
   from test_table
) t
where diff <> 0;

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!