Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to nearest date in the future to between today with sql (mysql)

I want to see the report date with the nearest future date. I want it to be a single record based on implementation id. Today 02-18-2022

SELECT   *
   FROM     document_reports
   WHERE    reportDate >= now() AND reportDate in 
   (SELECT MIN(reportDate) 
   FROM document_reports 
   WHERE reportDate >= NOW()
   group by implementation_id )
   
   group by implementation_id
   order by reportDate

You can check the tables in the below

 You can check the tables in the below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please help me? Where did I make mistake?

>Solution :

If it’s MySQL 5.x, then I’d use a correlated sub-query, or a join on an aggregate sub-query…

SELECT
  *
FROM
  document_reports
WHERE
  reportDate = (
    SELECT MIN(reportDate)
      FROM document_reports   AS lookup
     WHERE lookup.implementation_id  = document_reports.implementation_id
       AND lookup.reportDate        >= NOW()
  )
ORDER BY
  reportDate

Or...

SELECT
  document_reports.*
FROM
(
  SELECT implementation_id, MIN(reportDate) AS minReportDate
    FROM document_reports
   WHERE reportDate >= NOW()
GROUP BY implementation_id
)
  AS lookup
INNER JOIN
  document_reports
    ON  document_reports.implementation_id = lookup.implmentation_id
    AND document_reports.reportDate        = lookup.minReportDate
ORDER BY
  document_reports.reportDate

If it’s MySQL 8 then I’d use ROW_NUMBER()

WITH
  sorted AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY implementation_id
                           ORDER BY reportDate
                      )
                        AS rn
  FROM
    document_reports
  WHERE
    reportDate >= NOW()
)
SELECT
  *
FROM
  sorted
WHERE
  rn = 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading