CREATE TABLE t
(STUDENT int, SCORE int, DATE date)
;
INSERT INTO t
(STUDENT, SCORE, DATE)
VALUES
(1, 6, '2022-02-01 00:00:00'),
(1, 2, '2022-03-12 00:00:00'),
(1, 5, '2022-04-30 00:00:00'),
(2, 2, '2022-04-12 00:00:00'),
(2, 0, '2022-04-17 00:00:00'),
(2, 7, '2022-05-08 00:00:00'),
(3, 2, '2022-03-16 00:00:00'),
(3, 6, '2022-03-18 00:00:00'),
(3, 2, '2022-04-02 00:00:00'),
(3, 9, '2022-04-27 00:00:00'),
(4, 4, '2022-02-24 00:00:00'),
(4, 0, '2022-02-26 00:00:00'),
(5, 3, '2022-01-28 00:00:00'),
(5, 0, '2022-02-21 00:00:00'),
(5, 4, '2022-04-05 00:00:00')
;
I wish to make a file like this:
The rules is:
- Find min(DATE) when SCORE = 2 and compare to min(DATE) when SCORE = 6
A. If min(DATE, SCORE = 2) < min(DATE, SCORE = 6) then FLAG equals to 1
B. If min(DATE, SCORE = 2) >= min(DATE, SCORE = 6) then FLAG equals to 0
A. If STUDENT has record for SCORE = 2 but no record for SCORE = 6, then FLAG equals to 1
2
Answers
Here you use the same approach with LEFT JOIN
You can use here –
MySQL CASE statement
Below is the query to get the desired result.
Here, I have used a CTE (Common Table Expression) to make the query more readable.
Demo: https://onecompiler.com/mysql/3zpma8neh