sql >> Database teknologi >  >> RDS >> Oracle

Nulstille en kumulativ sum?

Du skal identificere grupper af på hinanden følgende dage, hvor oos =1 eller 0. Dette kan gøres ved at bruge LAG-funktionen til at finde, hvornår oos-kolonnen ændres, og derefter summere over det.

with x (s_date,qty,oos,chg) as (
  select s_date,qty,oos,
         case when oos = lag(oos,1) over (order by s_date)
                then 0
                else 1
         end
  from stk
  )
select s_date,qty,oos,
       sum(chg) over (order by s_date) grp
from x;
 

output :

| S_DATE | QTY | OOS | GRP | |--------------------------------|-----|-----|-----| | January, 01 2013 00:00:00+0000 | 0 | 1 | 1 | | January, 02 2013 00:00:00+0000 | 0 | 1 | 1 | | January, 03 2013 00:00:00+0000 | 0 | 1 | 1 | | January, 04 2013 00:00:00+0000 | 5 | 0 | 2 | | January, 05 2013 00:00:00+0000 | 0 | 1 | 3 | | January, 06 2013 00:00:00+0000 | 0 | 1 | 3 |

Derefter kan du summere over dette oos, opdelt efter grp-kolonne for at få på hinanden følgende oos-dage.

with x (s_date,qty,oos,chg) as (
  select s_date,qty,oos,
         case when oos = lag(oos,1) over (order by s_date)
                then 0
                else 1
         end
  from stk
  ),
y (s_date,qty,oos,grp) as (
  select s_date,qty,oos,
         sum(chg) over (order by s_date)
  from x
  )
select s_date,qty,oos,
       sum(oos) over (partition by grp order by s_date) cum_days_oos
from y;
 

output:

| S_DATE | QTY | OOS | CUM_DAYS_OOS | |--------------------------------|-----|-----|--------------| | January, 01 2013 00:00:00+0000 | 0 | 1 | 1 | | January, 02 2013 00:00:00+0000 | 0 | 1 | 2 | | January, 03 2013 00:00:00+0000 | 0 | 1 | 3 | | January, 04 2013 00:00:00+0000 | 5 | 0 | 0 | | January, 05 2013 00:00:00+0000 | 0 | 1 | 1 | | January, 06 2013 00:00:00+0000 | 0 | 1 | 2 |

Demo på sqlfiddle.



  1. SQL Server:ækvivalent drop tabel kaskade?

  2. Størrelse på partitionstabel i PostgreSQL 9.0

  3. Lagret procedure, der automatisk sletter rækker ældre end 7 dage i MYSQL

  4. Design af en Microsoft T-SQL Trigger