1. Think about the three bright color columns are from your original table.
2. Insert two columns to the right of the blue column.
3. Insert one row to the top.
4. Put this formula in C2: =B2+C1*($A2=$A1), drag to the last CFC row.
5. Put this in D2: =($A2 <>$A3)*(C2>0), then drag to the last CFC row.
6. Leave the bottom black row empty and summarize the column D in the next row (the 5 row).
7. Go to the blue 5 cell, make it equal to the 5 row at column D.
8. Now you copy column C and D to columns F and G.
9. Repeat the 7th step to make those cells with '2'.
10. Now hide C, D, F, G together with the two black rows. You will see the results you wanted.
11. You can change the numbers freely to see how the bottom numbers 5 and 2 will change accordingly.
12. Adding rows to the table might cause you a little trouble, hopefully you can fix it by yourself.
13. Important step: Give your CFC cash to me if you do think this is helpful.