Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Query in one step

$
0
0

I have available quantity of some product on my stock in different warehouses.
Now, i have to take some quantity from stock.
I have to take it from warehouse based on priority order.

Every product has some packing unit, for example 10 pieces in one package.
If there is quantity less than packing unit in some warehouse i have to take it on the end.

I should not take all quantity from one warehouse but 10% from every warehouse until I take all required quantity.

I think that the following example is clear enough.

Can someone create a query in one step? Or at least with the less possible steps. I have tried with recursion but with no success so far. If possible without cursor.

CREATE TABLE #test(whId INT, availQ INT, priority tinyint)

INSERT INTO #test(whId, availQ, priority) VALUES
(1, 100, 1),(2, 5, 1),(3, 40, 2),(4, 30, 2),(5, 60, 2),(6, 20, 3),(7,10,3)

--I need to take quantity=250, 10% on each step, order by priority and quantity
--taking by packing unit=10, if doesn't exist enywhere more than packing unit than take what exists

--step 1: priority 1(first take from the highest priority warehouse): 10%=33, qRemain=qRequired=250

UPDATE #test SET availQ=67 WHERE whId=1
--(whId=2 has quantity less than packing unti, so leave it untill the end)

--step 2, stil priority 1, qRemain=250-33=217:
UPDATE #test SET availQ=34 WHERE whId=1

--step 3: stil priority 1, qRemain=217-33=184:
UPDATE #test SET availQ=1 WHERE whId=1

--step 4: stil priority 1, qRemain=184-33=151:
--now there doesn't exist record with quantity greater than packing unit and priority 1, so take what is left(order by quantity):
UPDATE #test SET availQ=0 WHERE whId=2
UPDATE #test SET availQ=0 WHERE whId=1

--step 5: go to priority 2(since priority 1 is already all used), qRemain=151-1-5=145:
UPDATE #test SET availQ=27 WHERE whId=5
UPDATE #test SET availQ=7 WHERE whId=3

--step 6: still priority 2(no row with availQ>qPack), qRemain=145-33-33=79:
UPDATE #test SET availQ=0 WHERE whId=4
UPDATE #test SET availQ=0 WHERE whId=5
UPDATE #test SET availQ=0 WHERE whId=3

--step 7: go to priority 3, qRemain=79-30-27-7=15
--priority 3 are two warehouses with availQ lower than packing unit, so, take the row with greater Q:
UPDATE #test SET availQ=5 WHERE whId=6

DELETE FROM #test WHERE availQ=0

--at the end I have in my stock available quantity=5 on warehouse id =6 and 10 on warehouse id=7
SELECT * FROM #test

DROP TABLE #test


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>