开发者

SQL Server Database query help

开发者 https://www.devze.com 2022-12-27 01:57 出处:网络
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 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 o开发者_如何学运维pen (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,


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
0

精彩评论

暂无评论...
验证码 换一张
取 消