Q:

How to make a rule by sql please?

I have a table named flup and some datas like:
pid, flup_time, degree, oc, flup_type

1, 2018-05-06, 1, 0, 2

1, 2018-08-01, 2, 0, 3

1, 2018-08-13, 2, 0, 1

1, 2018-08-25, 2, 1, 1

1, 2018-11-20, 2, 1, 2

1, 2019-01-09, 2, 1, 2

2, 2018-06-01, 1, 0, 2

2, 2018-08-27, 2, 0, 2

2, 2018-11-30, 2, 0, 2
...

First, find all datas group by pid, for this pid (here pid=1), order by flup_time asc. Give a period of time (like from 2018-01-01 to 2019-07-01), for every row, make rules:
rule1. if degree = 1, then next flup_time must in 90 days.
rule2. if degree = 2 and oc != 1, then next flup_time must in 15 days.
rule3. if degree = 2 and oc = 1, then next flup_time must in 90 days.
I want to create a view (flup_view), has all the columns of flup, and more column named pass_check. If the row met the rule1,2,3, pass_check = 1, otherwise pass_check = 2. Like:
pid, flup_time, degree, oc, flup_type, pass_check

1, 2018-05-06, 1, 0, 2, -1

1, 2018-08-01, 2, 0, 3, 1

1, 2018-08-13, 2, 0, 1, 1

1, 2018-08-25, 2, 1, 1, 1

1, 2018-11-20, 2, 1, 2, 1

1, 2019-01-09, 2, 1, 2, 1

2, 2018-06-01, 1, 0, 2, -1

2, 2018-08-27, 2, 0, 2, 1

2, 2018-11-30, 2, 0, 2, 2

How to do this by sql please?

A:

There are a couple of pieces that you'll need for this to work. I'm not sure how strong your SQL background is, so I'll include the basics as well.
First, in order to create the rule, you'll need to use a CASE WHEN:
https://www.w3schools.com/sql/func_mysql_case.asp
Next, you need to get the following row for each ID, you need to use the LEAD function. Here's a general overview:
https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html
and a tutorial for LAG, which is the same as LEAD, but it checks the row above rather than the row below:
http://www.mysqltutorial.org/mysql-window-functions/mysql-lag-function/
(LEAD didn't exist in early version of MySQL, so your version might not have this)
Finally, you want to compare dates using the DATE_ADD function:
https://www.w3schools.com/sql/func_mysql_date_add.asp
It will be a little complicated, but these three things should be enough to let you build the query you need.

