Skip to content
Advertisement

mySQL Select All where date is less than 1 day from max date in data

I am having a table name “raw”. The date column is not having all the dates of month as it does not record holidays or when there were no sales for the day. I am trying to get the data form the date less than a day of specific date or max date but it is not returning the search as before the max date was holiday. here are the dates: 2021-07-09 2021-07-07 2021-07-03 2021-07-02 2021-07-01 2021-06-30

SELECT *
    FROM raw
    WHERE date=(SELECT MAX(date) - 1 FROM raw);

or

SELECT *
FROM raw
WHERE date=(SELECT MAX(date) - interval 1 day FROM raw);

    begin{table}[]
begin{tabular}{lll}
Name  & Date       & Sales \
ACC   & 2020-07-09 & 2000  \
BEL   & 2020-07-09 & 200   \
Dabur & 2020-07-09 & 600   \
ACC   & 2020-07-07 & 450   \
GMR   & 2020-07-07 & 12    \
ACC   & 2020-07-03 & 450   \
ITC   & 2020-07-03 & 45    \
Dabur & 2020-07-03 & 350   \
GMR   & 2020-07-03 & 450   \
BEL   & 2020-06-30 & 500   \
GTL   & 2020-06-30 & 850   \
Dabur & 2020-06-30 & 100   \
ACC   & 2020-06-27 & 50    \
Dabur & 2020-06-27 & 125  
end{tabular}
end{table}

Advertisement

Answer

If you want the data from the day before a specific date, then use:

SELECT r.*
FROM raw r
WHERE r.date = (SELECT MAX(r2.date) FROM raw r2 WHERE r2.date < ?);

The ? is the specific date.

For the date previous to the maximum date, you could use:

SELECT r.*
FROM raw r
WHERE r.date = (SELECT MAX(r2.date)
                FROM raw r2
                WHERE r2.date < (SELECT MAX(r2.date) FROM raw r3)
               );

Ouch. Two levels of subqueries. That seems cumbersome. A simpler method is:

SELECT r.*
FROM raw r
WHERE r.date = (SELECT DISTINCT r2.date
                FROM raw r2
                ORDER BY r2.DATE DESC
                LIMIT 1 OFFSET 1
               );
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement