Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return the row where before and after value is lower

I have a table that looks like this:

name         val
1            1
2            2
3            1
4            2
5            2
6            10

For each row, I want to check if there’s an increase in the value as compared to the last value. Then, I want to return the rows where the previous and next value is lower. For example, in this case, I want to return

name         val
2            2

but not any of the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

4            2
5            2
6            10

since there’s a constant increase till the end of the table and no decrease at the end. Ideally, I would also like to order the table by the namecol before I start comparing the val.

>Solution :

you can write a query using lead and lag functions like below

select name, val 
from 
(select *,
 CASE WHEN LAG(val) OVER( ORDER BY name) IS NULL THEN 
val ELSE LAG(val) OVER( ORDER BY name) END asd prev_value,
    CASE WHEN LEAD(val)  OVER( ORDER BY name) IS NULL THEN val ELSE LEAD(val)  OVER( ORDER BY name) END as next_value
    from yourtable 
    )T
    where prev_value<val AND val> next_value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading