I have a view with a list of relative seconds for a foreign key (ID):
CREATE TABLE Times ( ID INT , TimeFrom INT , TimeTo INT );
The table contains mostly non-overlapping data, but there are times when I have a TimeTo <TimeFrom of another record:
+----+----------+--------+ | ID | TimeFrom | TimeTo | +----+----------+--------+ | 10 | 10 | 30 | | 10 | 50 | 70 | | 10 | 60 | 150 | | 10 | 75 | 150 | | .. | ... | ... | +----+----------+--------+
The result set is designed to smooth out a linear downtime report, but with too many of these overlaps, I get negative usage time. That is, if the window ID = 10 above was 150 seconds, and I calculated the difference in relative seconds to subtract from the window size, I would end with 150-(20+20+90+75)=-55 . I tried this approach, and it led me to understand the presence of overlaps that needed to be smoothed out.
So, what I'm looking for is a solution to smooth out overlaps one set of times:
+----+----------+--------+ | ID | TimeFrom | TimeTo | +----+----------+--------+ | 10 | 10 | 30 | | 10 | 50 | 150 | | .. | ... | ... | +----+----------+--------+
Considerations: performance is very important here, as it is part of a larger request that will work well on it, and I don't want to greatly affect its performance if I can help it.
In the comment on “What seconds is the interval”, this is what I tried for the final result, and I'm looking for something with better performance. Adapted to my example:
SELECT SUM(CN) FROM ( SELECT AN, ROW_NUMBER()OVER(ORDER BY AN) RowID FROM (SELECT TOP 60 1 N FROM master..spt_values) A , (SELECT TOP 720 1 N FROM master..spt_values) B ) C WHERE EXISTS ( SELECT 1 FROM Times SE WHERE SE.ID = 10 AND SE.TimeFrom <= C.RowID AND SE.TimeTo >= C.RowID AND EXISTS ( SELECT 1 FROM Times2 D WHERE ID = SE.ID AND D.TimeFrom <= C.RowID AND D.TimeTo >= C.RowID ) GROUP BY SE.ID )
The problem with this solution is that I get the Row Count Spool from the EXISTS query in the query plan with the number of executions equal to COUNT (C. *). I left the real numbers in this query to illustrate that getting around this approach is best. Because even with the Row Count Spool, which significantly reduces the cost of the request, the execution counter also increases the cost of the request as a whole.
Further editing. The ultimate goal is to put this in the procedure, so variable tables and tone tables are also a possible tool to use.