Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

MySQL:cara memilih catatan dengan tanggal terbaru sebelum tanggal tertentu

Anda dapat menambahkan NOT EXISTS untuk pertanyaan Anda:

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 )

Demo di sini

Sunting:

Anda dapat menggunakan kueri berikut yang juga mempertimbangkan kasus memiliki beberapa tanggal aktivasi:

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)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Json MySql mendapatkan Dua Integer dan sebuah String

  2. Sisipan Python MySql tidak berfungsi

  3. Bagaimana catatan/logika fanout ini diturunkan untuk kasus tanpa statistik di Perencana Kueri MySQL?

  4. Alternatif pt-query-digest - Manajemen &Pemantauan Kueri MySQL dengan ClusterControl

  5. MySQL Split Comma Dipisahkan String Ke Tabel Temp