I'm not really sure that the title actually corresponds, maybe my approach is wrong.
I have the following database structure:
TABLE producers
id
TABLE data
id
date
value
producer_id OneToMany
First thing first, for each producer, I want to get the latest date of registered data that there is. The code below does exactly this:
SELECT producers.id AS producer_id, max.date AS max_date
FROM producers
INNER JOIN data ON producers.id = data.producer_id
INNER JOIN (
SELECT producer_id, MAX(date) AS date
FROM data
GROUP BY producer_id
) AS max USING (producer_id, date)
And the resulting table is:
----------------------------------------------------
| producer_id | max_date |
----------------------------------------------------
| 5 | 2022-01-01 01:45:00.000 +0000 |
| 7 | 2022-01-01 01:45:00.000 +0000 |
| 14 | 2022-01-01 01:45:00.000 +0000 |
| 15 | 2022-01-01 01:45:00.000 +0000 |
| 17 | 2022-01-01 01:45:00.000 +0000 |
----------------------------------------------------
The next thing that I need is to SUM all the data records per producer WITH date bigger than the max_date we got for each producer after the INNER JOIN from the previous query. The SUM() will be performed on column value.
Hopefully that was clear, if not, let me know. I've tried doing another INNER JOIN and use table max in the WHERE clause but I got an error that told me that the table was there, but it wasn't possible to be used in that part of the query.
Maybe another INNER JOIN isn't the solution. Here I'm limited by my knowledge of SQL and I don't really know about which keywords to read more in-depth to understand what's the best approach and how to do it. So, an info to redirect me on the best path would be really helpful.
Thanks in advance.
EDIT: Forgot to specify on which column the SUM() will be executed on.
EDIT 2: Just realized that what I'm asking here, the result will always be an empty table because there won't ever be a record whose date will be bigger. When I wrote the simplified version of my database, forgot to add a table/join, that's why. But in the end imo the approach/solution will still be the same, just applied on a different table. Sorry for that again.
sum()?valueINNER JOINs beside this one, so that's why I cannot do it this way. But I'll remember, thanks.