SQL lists n number of same items from DB, first come first expiry with stock avail and second come second expiry for example I have panadol total of 7 among 2 of them expire on May and 5 will expire November.
What I want to achieve is customer wants to buy 6 panadol, then list 2 items with shorter expiry and 4 item with a longer expiry
Here is table
stockId |
Item |
Stock |
Expiry |
5 |
Panadol |
2 |
30.05.2024 |
15 |
Panadol |
5 |
30.11.2025 |
Expected Result When a customer wants to buy 6
stockId |
Item |
Stock |
quantity |
Expiry |
5 |
Panadol |
2 |
2 |
30.05.2024 |
15 |
Panadol |
5 |
5 |
30.11.2025 |
Expected Result When a customer wants to buy 2
stockId |
Item |
Stock |
quantity |
Expiry |
5 |
Panadol |
2 |
2 |
30.05.2024 |
WITH RankedInventory AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Item ORDER BY Expiry) AS rn
FROM
Inventory
WHERE
Item = 'Panadol' AND
QuantityAvailable > 0
)
SELECT
*
FROM
RankedInventory
WHERE
rn <= 2