Home > other >  How to get all records with the last two dates
How to get all records with the last two dates

Time:11-02

I have a table with dates and some other information, where the dates are not continuous (no weekends). How do I get all records from the last two days/dates (which I don't necessarily know beforehand)?

While

SELECT datum FROM trackproc ORDER BY datum DESC LIMIT 1;

gives me the last date, and

SELECT datum FROM trackproc ORDER BY datum DESC LIMIT 1,1;

the second last one, which is what I want, this statement

SELECT * FROM trackproc 
WHERE datum BETWEEN (SELECT datum FROM trackproc ORDER BY datum DESC LIMIT 1) 
            AND     (SELECT datum FROM trackproc ORDER BY datum DESC LIMIT 1,1) 
ORDER BY datum;

returns empty.

How would I write such a statement?

CodePudding user response:

Just try this

SELECT *FROM trackproc WHERE datum BETWEEN DATE_SUB(DATE(NOW()), INTERVAL 2 DAY) AND DATE_SUB(DATE(NOW()), INTERVAL 1 DAY);

CodePudding user response:

You first need to find the DISTINCT datum values in your record set and get the last 2. Then get all records that have the same date.

SELECT b.*
FROM
(
    SELECT DISTINCT(datum) AS datum
    FROM trackproc
    ORDER BY 1 DESC
    LIMIT 2
) AS a
INNER JOIN trackproc AS b ON a.datum=b.datum;
  • Related