Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
Get variable MIN Date based on marker in row

I'm using MySQL with phpMyAdmin, below is my data table:

+--------+---------+-----------------+
| userID | context |      time       |
+--------+---------+-----------------+
|    111 |         | 7/1/2021        |
|    111 |         | 7/16/2019       |
|    111 | Reset   | 7/15/2019       |
|    222 |         | 7/9/2020        |
|    222 | Reset   | 7/8/2020        |
|    333 | Reset   | 5/11/2020       |
|    333 |         | 5/10/2020       |
|    444 |         | 9/8/2020        |
+--------+---------+-----------------+

I'm looking for a SELECT query that gives me the MIN time greater or equal to the date where a Reset is logged in the context column. If no Reset marker exists in the context column, I'd like to have the result included.

So for the table above, I expect the result:

+--------+-----------------+
| userID |      time       |
+--------+-----------------+
|    111 | 7/15/2019       |
|    222 | 7/8/2020        |
|    333 | 5/11/2020       |
|    444 | 9/8/2020        |
+--------+-----------------+

I tried :

SELECT * FROM foo as a 
WHERE ((SELECT MIN(a.time) FROM foo) >= (SELECT Max(a.time) FROM foo where context = 'Reset')) group by userID

does not produce my expected output, but returns:

+--------+-----------+
| userID |   time    |
+--------+-----------+
|    111 | 7/1/2021  |  <--- wrong 
|    222 | 7/8/2020  |
|    333 | 5/11/2020 |
+--------+-----------+
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use window functions:

select t.*,
       coalesce(next_time, time) as imputed_time
from (select t.*,
             sum(context = 'reset') over (partition by user_id) as cnt_reset,
             min(case when context is null then time end) over (partition by userid order by time rows between current row and unbounded following) as next_time
      from t
     ) t
where cnt_reset = 0 or context = 'reset';
over 4 years ago · Santiago Trujillo Report

0

Basis on your expected result, You may try below query -

SELECT userID, MAX(time)
  FROM YOUR_TABLE
 WHERE context = 'RESET'
 GROUP BY userID
 UNION ALL
SELECT userID, MAX(time)
  FROM YOUR_TABLE
 WHERE context IS NULL
 GROUP BY userID
 ORDER BY userID
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!