For an application I make, I need to get the last week (monday to friday) and the details for every day for each user I have in the database.
For now, my query gets every day of the month starting to today (So if we're the 18th, it'll get 18-17-16... and so on) and the month before (in case we're the first...)
But I want to limit the select to the first 8 days. I read this:
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
The last example is what I'm trying to do. But the problem is that I need to do an order by before. I need to order by months (DESC), than by days (DESC) and than I need to do the having to get what I want. I tried it without ordering, it works well, but it gets the wrong days. Because by default it's ordered ASC.
Just for the example, here's a query that represent my problem, here's what I have:
SELECT 
    day, id 
FROM 
    myTable 
WHERE 
    (month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 1 OR 
         month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 2) AND 
    year = EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AND 
    day <= EXTRACT(DAY FROM CURRENT_TIMESTAMP) 
ORDER BY 
    month DESC, 
    day DESC;
Here's what I want:
set @day := 0, @id:= '';
SELECT 
    day, id, @day := if(@id= id, @day + 1, 1) as day_number,
    @id := id as dummy 
FROM 
    myTable 
WHERE 
    (month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 1 OR 
         month = EXTRACT(MONTH FROM CURRENT_TIMESTAMP) - 2) AND 
    year = EXTRACT(YEAR FROM CURRENT_TIMESTAMP) AND 
    day <= EXTRACT(DAY FROM CURRENT_TIMESTAMP) 
ORDER BY 
    month DESC, 
    day DESC 
HAVING 
    day_number <= 8;
But I can't put a HAVING after an ORDER BY. If I remove the ORDER BY clause, I'll get all days for every id between 1st and 8th. But I need between 18th and 10th. (18th being the current date)
With the code I have in the app, it will stop after a week, so it doesn't matter if the select returns sunday to saturday, I just want to have at least monday to friday. Which is why I took the number '8', because the app will execute this only mondays.
Thanks for any help/suggestion!
 
    