I have quite simple problem in SQL Server:
User can have 12 items that are represented in table with ID and Slot (slot is 0-11). When an item is picked up, it should be placed into the lowest empty slot.
I am using following script but it returns first empty slot after the first used slot:
SELECT coalesce ((SELECT MIN(Slot) + 1 FROM Items N1 WHERE N1.name = 'abc'
AND NOT EXISTS(SELECT * FROM Items N2 WHERE N2.name = 'abc'
AND N2.Slot = N1.Slot + 1) AND Slot<11),0)
I would need the script to find lowest slot that does not exist yet. Hope it makes sense 🙂
An example – if the table contains following records, it does not work, returns 5 (should return 0):
ID Slot Name
10 3 abc
11 4 abc
With this data, it does return 2 correctly.
ID Slot Name
10 0 abc
11 1 abc
The script should return 1 as this is the first not used number (Slot) lower than 11.
1 Answer