I need to do a SUM of the last value (by date) of each day of the current week. To test I have a table with the values:
5 for 2023-01-12 16:53:01
2 for 2023-01-12 08:49:03
5 for 2023-01-11 08:58:19
I expect a result of 10.
I’m trying with the following code:
SELECT SUM(value) AS weeklyValue
FROM (
SELECT value
FROM table
WHERE WEEK(DATE(DataOra)) = WEEK(NOW())
AND WEEKDAY(DATE(DataOra)) >= 1
AND WEEKDAY(DATE(DataOra)) <= 7
AND DataOra = (SELECT MAX(DataOra) FROM table WHERE WEEKDAY(DataOra) = WEEKDAY(DATE(DataOra)) )
GROUP BY WEEKDAY(DATE(DataOra))
) AS subquery;
but the result is 5. Where is the mistake? Thanks
4
Answers
Maybe I found a solution:
You can do it using
inner join
as follows :Check it here : https://dbfiddle.uk/hadzywwh
If I really understood what you want, this request may be (if I understood correctly, I am specifying) the solution
The trick to find the most recent date of the day being to group by day number with the max() function on dateTime Data.
So, let’s start by constraining our working set to just the current week’s data –
Then we can use that to constrain the query used to get the MAX(DataOra) per DATE(DataOra) and join back to the original dataset to get the sum of the respective
Value
s –Or if using MySQL >= 8.0 you could use the ROW_NUMBER() window function –