By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE widgets (indate DATE , widgetID VARCHAR(12), price FLOAT , expirydate DATE) ;
INSERT INTO widgets VALUES
('2020-01-01','A' ,1 ,'2020-03-01')
,('2020-01-01','B' ,2 ,'2020-04-01')
,('2020-01-01','C' ,3 ,'2020-05-01')
,('2020-01-01','D' ,4 ,'2020-06-01')
,('2020-01-02','A' ,1.1 ,'2020-03-01')
,('2020-01-02','B' ,2.05 ,'2020-04-01')
,('2020-01-02','C' ,3.7 ,'2020-05-01')
,('2020-01-02','D' ,3.8 ,'2020-06-01')
,('2020-01-03','A' ,1.15 ,'2020-03-01')
,('2020-01-03','B' ,2.09 ,'2020-04-01')
,('2020-01-03','C' ,3.54 ,'2020-05-01')
,('2020-01-03','D' ,4.2 ,'2020-06-01')
,('2020-01-04','A' ,1.19 ,'2020-03-01')
,('2020-01-04','B' ,2.14 ,'2020-04-01')
,('2020-01-04','C' ,3.73 ,'2020-05-01')
,('2020-01-04','D' ,4.30 ,'2020-06-01')
SELECT indate , widgetID , price , expirydate FROM (
SELECT * , ROW_NUMBER() OVER (PARTITION BY indate ORDER BY ABS(price - 1), ABS(DATEDIFF(expirydate, '2020-03-10')) ) rn1
, ROW_NUMBER() OVER (PARTITION BY indate ORDER BY ABS(price - 3.5), ABS(DATEDIFF(expirydate, '2020-05-15')) ) rn2
FROM widgets
) t
WHERE rn1 =1 OR rn2 = 1
ORDER BY indate , widgetID
indate | widgetID | price | expirydate |
---|---|---|---|
2020-01-01 | A | 1 | 2020-03-01 |
2020-01-01 | C | 3 | 2020-05-01 |
2020-01-02 | A | 1.1 | 2020-03-01 |
2020-01-02 | C | 3.7 | 2020-05-01 |
2020-01-03 | A | 1.15 | 2020-03-01 |
2020-01-03 | C | 3.54 | 2020-05-01 |
2020-01-04 | A | 1.19 | 2020-03-01 |
2020-01-04 | C | 3.73 | 2020-05-01 |