Consider a table representing a queue, with a datetime
timestamp for when an item has been added, and one for when it is completed.
The question: How can I efficiently query for any given time, how many items were in queue, ie. added but not completed.
A table sample example:
id value added completed
6 1 2016-01-01 00:00:12.345 2016-01-01 00:01:12.345
7 500 2016-01-01 01:12:12.345 2016-01-01 01:15:12.345
8 1 2016-01-01 01:12:12.345 2016-01-01 02:16:12.345
9 2 2016-01-01 01:33:12.345 NULL
10 2 2016-01-01 01:33:12.345 NULL
11 2 2016-01-01 01:33:12.345 NULL
Items can be added at any time, but it takes time for them to be completed.
In the example above, 9, 10 and 11 are under process, so I can easily query to find that 3
items are in queue right now. But how do I query to find for example how many items were in queue and not completed at any given past time?
I am looking for a result that looks something like this:
date time count sum value
2016-01-01 00:00:00.000 1 1
2016-01-01 00:12:00.000 2 501
2016-01-01 00:13:00.000 2 501
2016-01-01 00:14:00.000 2 501
2016-01-01 00:15:00.000 1 1
2016-01-01 00:33:00.000 3 6
My goal is to find the times with max number of items in queue. From here I would be able to say that the queued item size was highest at 00:33 and that the queued value size was the highest 00:12-00:14.
What I've tried: I have experimented with WITH
like suggested in this answer. It works fine for only one date, but when I use both hs.added>= DATEADD(...
and hs.completed >= DATEADD(
criteria, the execution that was 0 seconds now seen to never complete. I am not completely grasping the execution process here.
This large table is in production, and I do not want to keep a query executing for too long.
Edit: stats:
COLUMN_NAME DATA_TYPE CHARACTER_MAXIMUM_LENGTH IS_NULLABLE
ID int NULL NO
added datetime NULL NO
completed datetime NULL YES
value int NULL NO
CONSTRAINT_NAME
PK_Queue
name type_desc is_unique is_primary_key
PK_Queue CLUSTERED 1 1
IX_Queue_completed NONCLUSTERED 0 0
IX_Queue_added NONCLUSTERED 0 0
rows data
6 000 000 15 000 000 KB