I'm stuck writing a query for the following scenario: I have a table of things, they have a metric called number in the examples below. I have another table called offers which is a list of offers made on a particular thing. I'm looking for the highest offer on each thing that is less than or equal to the number on a thing.
I can't seem to come up with the right JOIN and MAX() to satisfy the query, and end up running in circles.
things table:
| id | number | description |
|---|---|---|
| 1 | 5 | Thing 1 |
| 2 | 10 | Thing 2 |
| 3 | 8 | Thing 3 |
offers table:
| thing_id | offer | description |
|---|---|---|
| 1 | 1 | thing 1 offer 1 |
| 1 | 3 | thing 1 offer 2 |
| 1 | 12 | thing 1 offer 3 |
| 2 | 9 | thing 2 offer 1 |
| 3 | 1 | thing 3 offer 1 |
| 3 | 8 | thing 3 offer 2 |
Desired output:
| thing_id | number | offered | thing_description | offer_description |
|---|---|---|---|---|
| 1 | 5 | 3 | Thing 1 | thing 1 offer 2 |
| 2 | 10 | 9 | Thing 2 | thing 2 offer 1 |
| 3 | 8 | 8 | Thing 3 | thing 3 offer 2 |