Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL:como selecionar registro com data mais recente antes de uma determinada data


Você pode adicionar NOT EXISTS à sua consulta:
SELECT t1.*
FROM user_status t1
WHERE t1.date_assigned = (SELECT MIN(t2.date_assigned)       -- the first occurance
                          FROM  user_status t2
                          WHERE t2.user_id =  t1.user_id     -- for this user
                          AND t2.status_id <> 1              -- where status not active
                          AND t2.date_assigned BETWEEN       -- within 1 yr of given date
                               '2015-05-01' + INTERVAL 1 DAY -- (not including that date)
                          AND 
                               '2015-05-01' + INTERVAL 1 YEAR 
                          )
      AND NOT EXISTS (SELECT 1                         -- such a record should not exist
                      FROM user_status t3
                      WHERE t3.user_id =  t1.user_id   -- for this user
                             AND t3.status_id <> 1     -- where status is not active
                             AND t3.date_assigned <    -- before the examined period
                               '2015-05-01' + INTERVAL 1 DAY )

Demonstração aqui

Editar:

Você pode usar a seguinte consulta que também considera o caso de ter várias datas de ativação:
SELECT *
FROM user_status
WHERE (user_id, date_assigned) IN (
  -- get last de-activation date   
  SELECT t1.user_id, MAX(t1.date_assigned)
  FROM user_status AS t1
  JOIN (
    -- get last activation date 
    SELECT user_id, MAX(date_assigned) AS activation_date
    FROM user_status 
    WHERE status_id = 1
    GROUP BY user_id
  ) AS t2 ON t1.user_id = t2.user_id AND t1.date_assigned > t2.activation_date
  GROUP BY user_id
  HAVING MAX(date_assigned) BETWEEN '2015-05-01' + INTERVAL 1 DAY AND '2015-05-01' + INTERVAL 1 YEAR AND
         MIN(date_assigned) > '2015-05-01' + INTERVAL 1 DAY)