By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
WITH data (date, widgetID, widget_price, widget_expiry_date) as (
select date '2020-01-01', 'A', 1 , date '2020-03-01' union all
select date '2020-01-01', 'B', 2 , date '2020-04-01' union all
select date '2020-01-01', 'C', 3 , date '2020-05-01' union all
select date '2020-01-01', 'D', 4 , date '2020-06-01' union all
select date '2020-01-02', 'A', 1.1 , date '2020-03-01' union all
select date '2020-01-02', 'B', 2.05 , date '2020-04-01' union all
select date '2020-01-02', 'C', 3.7 , date '2020-05-01' union all
select date '2020-01-02', 'D', 3.8 , date '2020-06-01' union all
select date '2020-01-03', 'A', 1.15 , date '2020-03-01' union all
select date '2020-01-03', 'B', 2.09 , date '2020-04-01' union all
select date '2020-01-03', 'C', 3.54 , date '2020-05-01' union all
select date '2020-01-03', 'D', 4.2 , date '2020-06-01' union all
select date '2020-01-04', 'A', 1.19 , date '2020-03-01' union all
select date '2020-01-04', 'B', 2.14 , date '2020-04-01' union all
select date '2020-01-04', 'C', 3.73 , date '2020-05-01' union all
select date '2020-01-04', 'D', 4.30 , date '2020-06-01'
),
params (date_, price_, expiry_date_) AS (
select date '2020-01-01', 1, date '2020-03-10' union all
select date '2020-01-03', 3.5, date '2020-05-15'
)
select data.*
from params p
join data on data.widgetID = (
SELECT widgetID
FROM data d
WHERE d.date = p.date_
ORDER BY ABS(DATEDIFF(d.widget_expiry_date, p.expiry_date_)) ASC, ABS(d.widget_price - p.price_) ASC
LIMIT 1)
;
date | widgetID | widget_price | widget_expiry_date |
---|---|---|---|
2020-01-01 | A | 1.00 | 2020-03-01 |
2020-01-02 | A | 1.10 | 2020-03-01 |
2020-01-03 | A | 1.15 | 2020-03-01 |
2020-01-04 | A | 1.19 | 2020-03-01 |
2020-01-01 | C | 3.00 | 2020-05-01 |
2020-01-02 | C | 3.70 | 2020-05-01 |
2020-01-03 | C | 3.54 | 2020-05-01 |
2020-01-04 | C | 3.73 | 2020-05-01 |