SQL Server: Get the position (sequence number) of a record in a table

I have a table in which the task queue is stored. Each task is as follows:

Id | Operation | Argument | Status

Operation - a string argument - a singular
status is one of: Queued, Busy, Complete,Failed

I need to find out the position of an element in the queue, but you need to skip tasks that are not queued.

Example:

1 A 5 Queued   -- 1
2 A 6 Queued   -- 2
3 B 3 Busy     -- x
4 B 4 Complete -- x
5 A 8 Queued   -- 3

The expected position followed by --position xmeans that the request does not make sense.

Question: what would be a good way to calculate such a position?
At the moment I am doing:

SELECT TOP 1 p.Position FROM
(
    SELECT Id, Status, 
    ROW_NUMBER() over (order by Id) as Position 
    from QueuedJobs where Status = 0 AND Id <= @taskId
) as p
order by Position desc

In English: Calculate the positions of each task before my task and give me the last position (this is my task)

, , 1000 (100 ).
- SQL Server 2008

+3
2

order by . , , ? FIFO? ? datetime. , , , .

+1

" 0" "", :

Select Count(*)
From QueuedJobs
Where Status = 0
  and Id <= @taskId

, :)

0

Source: https://habr.com/ru/post/1775869/


All Articles