I'm working in SAS and I have a table that looks like this

```
ID | Time | Main | lag_1 | lag_2
----------------------------------------------------------------------------
A  |  01  |   0  |   0   |  1  
A  |  03  |   0  |   0   |  1  
A  |  04  |   0  |   0   |  0  
A  |  10  |   1  |   0   |  0  
A  |  11  |   1  |   0   |  0  
A  |  12  |   1  |   0   |  0  
B  |  02  |   1  |   1   |  1  
B  |  04  |   0  |   1   |  1  
B  |  07  |   0  |   0   |  1  
B  |  10  |   1  |   0   |  0  
B  |  11  |   1  |   0   |  0  
B  |  12  |   1  |   0   |  0  

```

except with multiple IDs. The table is sorted by ID and Time. After calculating the total count of ones in the Main column (call it *tot*), I am trying to calculate 2 things:

1. The total count of ones in the Main column only if lag\_1 has been equal to 1 at some time **before** Main became 1, say *tot\_1*; and
2. The same as 1. but in this case for lag\_2, call the variable *tot\_2*

The table of expected calculations would give me that 

```
tot | tot_1 | tot_2
--------------------
 7  |   3   |   6

```

since *tot\_1* should be 3 (0 from ID = A + 3 from ID = B), and *tot\_2* should be 6 (3 from ID = A + 3 from ID = B).

I am a complete beginner in these types of segmentations so any help is greatly appreciated.

Edit: I would expect that tot\_2 >= tot\_1 because lag\_2 is built on events from Main which go longer back in time than lag\_1 does.