I have below two tables
~ What I am looking to do: I want to append the Price from Table 2 to Table 1. If the exact Quantity in Table 1 is not there in Table 2, take the closest max Quantity from Table 2 [i.e. 12 Quantity is not there in Table 2, the closest max is 20, so I want the price of that].
BUT in some cases there are no max Quantity values, which leads to some entries to fall out of my output. In this case, I am thinking to take the closest min Quantity from Table 2, to avoid some values to fall out of my output
So the result should look like:
I have tried below query but this does not account for taking the closest min Quantity when the closest max does not exist. Product_NR '20765' therefore falls out of my output. I'm thinking of 'case when' but not sure how to incorporate it below.
select
Product_NR,
Customer,
Quantity,
min(price)
from
( select distinct
t1.Product_NR,
t1.Customer,
t1.Quantity,
t2.price,
min(t2.quantity) over (partition by t1.product_NR) as Quantity_min
from Table_1 t1
left join Table_2 t2 on t1.Product_NR = t2.Product_NR
and t1.Quantity <= t2.Quantity
)
where t2.Quantity = Quantity_min
group by
Product_NR,
Customer,
Quantity


