sql >> Database teknologi >  >> RDS >> PostgreSQL

Øg kolonneværdien på en bestemt betingelse i SQL-forespørgsel på Postgresql

Brug lag() og kumulativ sum:

with query as (
select w.*,
       sum(case when week < prev_week + 2 then 0 else 1 end) over (partition by animal order by week) as grp
from (select w.*,
             lag(week) over (partition by animal order by week) as prev_week
      from test.walk w
     ) w
)
select
    animal, week, grp,
    dense_rank() over (order by animal, grp) as grp2
from query

Bemærk:Dette vil genstarte optællingen for hvert dyr - hvilket ser ud til at være den egentlige hensigt med det, du vil gøre. Definitionen af ​​problemet er lidt vanskelig, hvis du vil have grupperne adskilt efter dyr, men skal være inkrementelle. En metode er:

select w.*,
       sum(case when prev_week = week then 0 else 1 end) over (order by min_week, animal, week) as grp
from (select w.*,
             lag(week) over (partition by animal order by week) as prev_week,
             min(week) over (partition by animal) as min_week
      from test.walk w
     ) w;



  1. Sådan fungerer LIKE-operatøren i MariaDB

  2. MySQL strip ikke-numeriske tegn for at sammenligne

  3. SQLite JSON()

  4. Adgang 2016 For Dummies Cheat Sheet