I have the following tables:
MONKEY :
id | name |
---|---|
1 | John |
2 | Mary |
CHECK :
id | monkey_id | checkdate |
---|---|---|
1 | 1 | 2023-06-02 03:00:00 |
2 | 2 | 2023-08-24 14:30:00 |
3 | 1 | 2023-06-04 14:35:00 |
MEASUREMENTS :
id | check_id | length | width | weight |
---|---|---|---|---|
1 | 1 | 23.34 | 6.34 | 3.2 |
2 | 1 | 23.87 | 6.22 | NULL |
3 | 1 | 24.3 | 6.10 | NULL |
4 | 2 | 27.8 | 7.4 | NULL |
5 | 2 | 27.56 | 7.62 | NULL |
XMITTER :
id | check_id | channel | tune | attachstart | attachfinish | removed |
---|---|---|---|---|---|---|
1 | 3 | 534 | 2 | 2023-08-24 14:30:32 | 2023-08-24 14:45:00 | NULL |
2 | 1 | 532 | 1 | 2023-06-02 03:31:00 | 2023-06-02 03:35:00 | 2023-06-10 14:45:00 |
How would I retrieve a monkey with:
- Date of most recent check
- Multiple sets of length/width measurements are taken at the same time (and joined by check_id) – I would like to return the average of the most recent length/width measurements and weight which is usually only taken once during a check.
- The current transmitter if one is attached. A transmitter is attached if it doesnt have a removed date.
EXAMPLE RESULT SET :
monkey.id | last_check_date | newest_avg_length | newest_avg_width | newest_avg_width | channel | tune | channel_attach_start |
---|---|---|---|---|---|---|---|
1 | 2023-06-04 | 23.82 | 6.20 | 3.2 | 532 | 1 | 2023-06-02 |
There should be one result set for each monkey.
I have created a fiddle here – which is same structure (slightly different data).
*NB: The most recent measurements is on check 1. The most recent xmitter is on check 3.
2
Answers
This query assumes:
health_check
and set ofmeasurements
And, here is an updated version of your fiddle
P.S. It only returns for monkey_id 2, as this is the only monkey with measurements for its most recent check.