views:

59

answers:

1

Hi,

I have a Database (SQL Server) with table named 'ProcessData' and columns named 'Process_Name' (Data Type: nvarchar(50)), 'Start_At' (DataType: DateTime) and 'End_At' (Data Type: DateTime).

I need to know for each 'Time-Interval' (let's say 1 second) how many processes (Process_Name = PN) was open (after or equal to the 'Start_at' column and before or equal to the 'End_At' column) during this time (It can be a few rows with the same data).

Does anyone know how to make this query?

Many thanks,

A: 

For any interval, you just want something like:

SELECT COUNT(1)
FROM   ProcessData row
WHERE (row.Start_At >= @start AND row.Start_At < @end) -- starts in interval
OR    (row.End_At >= @start AND row.End_At < @end) -- ends in interval
OR    (row.Start_At < @start AND row.End_at >= @end) -- spans interval

(you don't need to worry about "entirely in this interval", since "starts in" and "ends in" covers that)

Note I'm assume that @start is inclusive and @end is exclusive, which is a pretty common way of doing it (avoiding double-counting on boundaries, etc) - but feel free to add / remove a few = on the inequalities. For example, to include both ends:

SELECT COUNT(1)
FROM   ProcessData row
WHERE (row.Start_At >= @start AND row.Start_At <= @end) -- starts in interval
OR    (row.End_At >= @start AND row.End_At <= @end) -- ends in interval
OR    (row.Start_At < @start AND row.End_at > @end) -- spans interval
Marc Gravell
Yes, that's what I did. but I want a query that will promote the 'Time-Interval' by ITSELF. And as result to get a table with tow columns, one for each time, and the second with how many open processes was open during this time.
menacheb
Do you have a list of the time-intervals? Perhaps a UDF or CTE?
Marc Gravell
No, I want to start from (for example: 2010/04/17 00:00:00) and check from this date each second how many processes was open until (for example: 2010/04/18 00:00:00).
menacheb
So your result must be a row with a timestamp (second) and the number of open processes? One row per second?
TomTom
Exactly........
menacheb
have a look at tally tables : http://www.sqlservercentral.com/articles/T-SQL/62867/
Gaby
@Gaby - I would if they didn't insist on registration.
Marc Gravell
@Marc, if you feel adventurous, the whole article is there. With some css manipulator (firebug) you can remove the overlay and the overflow:hidden and see the whole article ;)
Gaby