Home > Software engineering >  How to get records based on nearest greater value
How to get records based on nearest greater value

Time:08-10

The Table contains data as below

Note - Running Total is calculated with respect to Part

Part Quantity Running Total Stock
ABC 5 5 45
ABC 10 15 45
ABC 12 27 45
ABC 16 43 45
ABC 10 53 45
ABC 5 58 45
DEF 5 5 15
DEF 10 15 15
DEF 10 25 15
DEF 5 30 15

The requirement is to fetch records where the running total should be the equal or nearest greater value with respect to stock. In the table, For Part ABC the stock value is 45. 53 is the nearest number greater than 45. For Part DEF the Stock value 15. So the Output should be

Part Quantity Running Total Stock
ABC 5 5 45
ABC 10 15 45
ABC 12 27 45
ABC 16 43 45
ABC 10 53 45
DEF 5 5 15
DEF 10 15 15

CodePudding user response:

If I understand your requirement correctly a correlated subquery is one of a few methods you could use:

select * 
from t
where running_total - stock <= (
    select Min(t2.running_total - t2.stock)
    from t t2 
    where t.part = t2.part and t2.running_total - t2.stock >= 0
);

CodePudding user response:

Using LAG function

SELECT
    part,
    quantity,
    running_total,
    stock
FROM (   
SELECT 
    *,
    LAG(running_total, 1, 0) OVER (PARTITION BY part ORDER BY running_total) AS prev_running_total
FROM parts
) t
WHERE prev_running_total < stock

Output:

part quantity running_total stock
ABC 5 5 45
ABC 10 15 45
ABC 12 27 45
ABC 16 43 45
ABC 10 53 45
DEF 5 5 15
DEF 10 15 15

fiddle

  • Related