Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Based on previous records, stop sum fields

I have a table like this:

|id |   date     | point |
+---+------------+-------+
| 6 | 2022/01/06 |   9   |
| 5 | 2022/01/05 |   7   |
| 4 | 2022/01/04 |   1   |
| 3 | 2022/01/03 |   4   |
| 2 | 2022/01/02 |   6   |
| 1 | 2022/01/01 |   1   |

My goal is to obtain sum of points from date now to date that the point is greater than equal to 1 and stop sum of fields before that date.

In the example above (order by date), the answer is sum of points date now(2022/01/06) to the date 2022/01/04 and equals 9 + 7 + 1 = 17. Because the point value for date 2022/01/03 is equal to 4, therefore is not calculated in sum.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I read about CTE and Window Functoin however, I wasn’t able to implement them properly.

>Solution :

  1. Find the first row before (and including) the desired date whose point value is 1.
  2. Sum up that and everything newer than it up to (and including) the desired date.
select sum(point)
from points
where date between (
  select "date"
  from points
  where point = 1 and date <= '2022/01/06'
  order by "date" desc
  limit 1
) and '2022/01/06';

Demonstration

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading