Skip to content
Advertisement

Only include values from the latest timestamp into the query result

DB-Fiddle

Expected Restult:


As you can see in the table there are multiple TIMESTAMP per day.
Now, I want to query the sum of the sales_quantity for each TIMESTAMP but only the lates ones should be included.

Therefore, in the example the TIMESTAMP with 07:15:30 and 07:19:23 should be ignored.

I tried to go with this query:

However, I get the error Can't group on 'MAX(time_stamp)'.
How do I need to modify the query to get the expected result?

Advertisement

Answer

You need a condition with NOT EXISTS in the WHERE clause so that you aggregate only the rows with the latest time_stamp of each day:

See the demo.

If you are using MySql 8.0+ and not MariaDB 10.3 (like your fiddle) then you could also do it with FIRST_VALUE() window function:

See the demo.

Results:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement