Say I have 2 tables
owners
| owner | car_ids |
|---|---|
| John | 1, 2, 3 |
| Sue | 3, 4, 5 |
cars
| car_id | price | last_driven |
|---|---|---|
| 1 | 100 | 2022-01-01 |
| 2 | 200 | 2022-01-02 |
| 3 | 300 | 2022-01-03 |
| 4 | 400 | 2022-01-04 |
| 5 | 500 | 2022-01-05 |
| 6 | 600 | 2022-01-06 |
And I want to get the sum of the price of all the cars per driver, and when they last drove, so the data looks like:
| owner | total_worth | last_driven |
|---|---|---|
| John | 600 | 2022-01-03 |
| Sue | 1500 | 2022-01-06 |
How would I do that? I can't figure out how to aggregate over values in a different table joined by values in the array field.
So far what I've got is
SELECT distinct
owner,
car_id,
cars.worth,
cars.last_driven,
FROM `owners` cross join unnest(card_id) as car_id
join `cars` cars on cars.owner = owner
but this won't aggregate the data, it'll only output each row.
Thanks in advance!
