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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With