Let’s say I have a MySQL table
called points
with 4 columns (id, user_id, point, date)
. And, let’s consider these dummy rows for better understanding.
id | user_id | point | date |
---|---|---|---|
1 | 1 | 2 | 2000-01-01 |
2 | 1 | 3 | 2000-01-01 |
3 | 2 | 5 | 2000-01-01 |
4 | 2 | 1 | 2000-01-01 |
5 | 1 | 6 | 2000-01-02 |
6 | 2 | 2 | 2000-01-02 |
7 | 1 | 3 | 2000-01-03 |
8 | 2 | 6 | 2000-01-03 |
9 | 1 | 1 | 2000-01-04 |
10 | 1 | 9 | 2000-01-04 |
11 | 2 | 6 | 2000-01-04 |
12 | 1 | 7 | 2000-01-05 |
13 | 2 | 4 | 2000-01-05 |
14 | 1 | 1 | 2000-01-06 |
15 | 2 | 6 | 2000-01-06 |
I have two variables consecutive_days_to_achieve_reward=2
and per_day_min_points_to_achieve_reward=5
. Now, I want to know how many times
the users have passed this specific requirement.
So, the result for the above table would be:
user_id | times |
---|---|
1 | 2 2000-01-01 - 2000-01-02 2000-01-04 - 2000-01-05 |
2 | 1 2000-01-03 - 2000-01-04 |
I am getting no clue how to solve MySQL problems with laravel eloquent
dealing with cumulative summation
. Could someone assist me?
2
Answers
Not sure that I understand entirely. The query below does calculate the days that satisfy that requirement, but I am not sure what you are wanting for ‘times’ value ? It sounds like you want the number of groups of 2 or more days and not the absolute number of days there, although you could probably modify the query a bit to get that.
As for Laravel eloquent or the Query Builder you should be able to translate a working query to that format, but if you are not too familiar with Laravel I would get a working MySQL query first.
I at least ran your data through and it seems to give the correct result.
I would start with the following (replacing the user-defined variables with params):
Output:
The first CTE produces the following output, based on your sample data (rn added to aid understanding):
The second CTE outputs:
Although the above can be built up using Laravel’s Query Builder, I would probably pass the parameterized query to
DB::select()
.