最大计数范围交集(在 T-SQL 中)
假设我有一个包含一堆日期的表,例如:
declare @tbl table {
idx int primary key,
startdate datetime,
enddate datetime
}
我想找到开始日期和结束日期相交的最大行集(在现实世界中,开始日期和结束日期代表事件的开始和结束时间,并且我需要找到同时发生的最大事件数)。
在另一种编程语言中,我可能会按开始日期对所有条目进行排序,然后迭代每个条目一次,构建临时的交集集(跟踪生成的最大集)。但我不确定这是否是在 T-SQL 中表达这一点的最有效方法。帮助!
哦,它是 SQL Server 2000。:(
Let's say I have a table with a bunch of dates, e.g.:
declare @tbl table {
idx int primary key,
startdate datetime,
enddate datetime
}
And I want to find the largest set of rows where startdate and enddate intersect (in the real world, the start date and end date represents start and end times for events, and I need to find the maximum # of events occurring simultaneously).
In another programming language I might sort all entries by startdate, then iterate through each entry once, building a temporary set of intersections (keeping track of the largest set generated). But I'm not sure if this is the most efficient way to express this in T-SQL. help!
Oh, and it's SQL Server 2000. :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新以删除联合所有
这给出了开始会话的时间线,以及新会话开始时的并发会话计数:
要获取原始请求(具有最大并发性的并发会话集),您需要要运行此查询两次,一次获取最大并发会话数,一次获取具有最大并发次数的会话的开始日期,那么您必须获取这些会话。
已更新
好的,这里是检索最大并发会话的单个查询。我更改了测试数据以删除结束和开始的 ambibuos 重叠:
这给出了如下结果:
其内容如下:在
2009-01-02 00:00:00
上有 3 个并发会话 (3 、 1 和 2) 以及它们各自的开始和结束。有一个平局,在2009-01-03 00:00:00
上还有 3 个并发会话(1、2 和 4),其各自的开始和结束。性能里程可能会有所不同。使用 CTE 在 SQL 2005 中可以将查询编写简单一百万倍。
Updated to remove the union all
This gives the timeline of start session, with the count of concurent sessions at the moment new session starts:
To get the original request (set of concurent sessions with max concurency) you need to run this query twice, once to get the max concurent sessions and once to get the start dates of the sessions that have max concurent times, then you must get those sessions.
Updated
OK, so here the one single query that retrieves the max concurent sessions. I changed the test data to remove ambibuos overlaps of end and start:
This gives a result like:
which reads as follows: on
2009-01-02 00:00:00
there were 3 concurent sessions (3, 1 and 2) with they respective starts and ends. There is a tie, on2009-01-03 00:00:00
there were also 3 concurent sessions (1, 2 and 4) with their respective starts and ends.Performance milage may vary. The query can be written 1 million times simpler in SQL 2005 using CTEs.
试试这个(它接近你想要的我想......
哦,如果你的日期中有日期和时间,那么仅用实际日期部分替换此处的所有日期(去掉时间)
try this (it's close to what you want I think...
oh, If your dates have date and Time in them, then replace all the dates herein with actual date portion only (strip off the time)
另一种方法:
Another approach:
这个很短,很容易理解并且工作得很好:
This one is pretty short, easy to understand and works fine: