Skip to content
Advertisement

How to get the Exact Batch ID from stock table on the basis of Expiry Date?

I want to get the batch id from stock table on the basic of fifo expiry date. How to get it. I write a query it give the exact batch but batch id not accurate. Basically I want to Fetch the batch is of the product which expired first

The Stock Table is Like as

  Batch_ID   |  Product_ID  | Quantity | Is_Expiry |Expiry_Date | Location_ID
       6     |     148      |    90    |    1      | 2019-08-24 |     1
       4     |     148      |    75    |    1      | 2019-09-13 |     1
       2     |     148      |    0     |    1      | 2019-07-11 |     1

I write this Query

Select batch_id,min(datediff(expiry_date,now())) as Remaining_Days  From Stock Where Product_ID = '148' and quantity > 0  and Location_ID = '1'

Current Output

Batch_ID   | Remaining_Days 
   4       |    56

Expected Output:

Batch_ID   | Remaining_Days 
   6       |     56

Advertisement

Answer

You are using aggregate min function it gives you wrong output.you can use order by function for sorting.

Select batch_id,(datediff(expiry_date,now())) as Remaining_Days From stock 
Where Product_ID = '148' and quantity > 0  and Location_ID = '1'
order by Remaining_days
limit 1;

DEMO

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement