這是相當困難的。因此,該地區的供應商提供不同尺寸的籃子,您希望這些籃子能夠匹配所需的籃子。您想要提供多個籃子金額。
對於想要的籃子尺寸,您可以使用一個子查詢,而對於可用的籃子尺寸,則需要一個子查詢。您將後者加入到第一個中,然後根據可用性和價格按供應商和訂單進行彙總。
以下查詢應該指向正確的方向。我想以此爲基礎,您可以編寫您需要的查詢:
select
provider,
case when sum(missing) = 0 then
'available for ' || sum(price)
else
sum(missing) ' baskets not available'
end as offer
from
(
select
available.provider,
wanted.size,
greatest(wanted.amount - available.amount, 0) as missing,
wanted.amount * available.price as price
from
(
select 'S' as size, 2 as amount
union all
select 'M' as size, 5 as amount
union all
select 'L' as size, 16 as amount
) wanted
left join
(
select provider, size, amount, price
from baskets
where city = @city
and location = @location
) available on available.size = wanted.size
) balanced
group by provider
order by sum(missing), sum(price)
使用的標記dbms。 (許多產品都有自己的存儲過程版本,不符合ANSI SQL標準。) – jarlh
現在標記了它。 – Nysa