I have the following data of date and color in a mysql database
2023-01-28 red
2023-01-29 blue
2023-01-30 blue
2023-01-31 red
2023-02-01 blue
2023-02-02 blue
2023-02-03 blue
2023-02-04 blue
2023-02-05 red
How can I pull the closest date to current date from each month and the associated color? Example answer for above code would be
2023-01-31 red
2023-02-05 red
3
Answers
I do not have MySQL, therefore, I am going to use SQL Fiddle.
Steps 1 & 2 create the table and add the data. Step 3 will want to covert the date into YYYYMM format for grouping and aggregation. Then group by that new fields and the color, selecting the date that is the largest using the MAX() function.
I could have left the new column in the final results, but you did not have it in the result set. Therefore, use a derived table to get the result in the () inner statement and select the two fields (columns) you want in the outer statement.
The screen shot below shows everything together.
http://sqlfiddle.com/#!9/1700b5/7/0
As i mentioned in the comment to the question, you have to use MAX function.
I’m not sure i understand your requirements, but i think you want to get all instance of color which date is the newest…
SQLFiddle
Result:
I got your desired output.
https://dbfiddle.uk/92RoM59i