sqlssms-17

SUMIF then restart count


How can I do a SUMIF function so that it adds up values when the value in another column is "False", but then when it hits a value that is "True", it restarts the count over again, but includes the value of the first "True" encounter in the SUM calculation? I would also like it so that it adds up the value in chronological order.

I did some research and I think I need to use an over partition and make a row number column to call all row number = "1", but I'm not sure how to do this.

Edit: the Sum should also include the "distance" value for the first "true" value it encounters

Edit 2: Ultimately, I am trying to calculate the average distance each vehicle travels before an Alert is triggered to "True" which means it needs to be taken to the shop to be fixed. Perhaps there is a better way to do this than what I was originally thinking?

Sorry for the poor phrasing...


Solution

  • You want to define groups. It sounds like you want the definition to be the number of "trues" up to and including a given row. Then, you can do a cumulative sum within each group. So:

    select t.*,
           sum(distance) over (partition by vehicleid, grp
                               order by date
                               rows between unbounded preceding and current row  
                              )    
    from (select t.*,
                 sum(case when alert = 'True' then 1 else 0 end) over
                     (partition by vehicleid
                      order by date
                      rows between unbounded preceding and current row
                     ) as grp
          from t
         ) t;
    

    Here is a db<>fiddle that illustrates that this code works.