从表中选择连续范围
我需要根据连续数字(N 列)和这些数字相关的相同“类别”(下面的 C 列)从表中提取连续范围。从图形上看,它看起来像这样:
N C D
--------
1 x a C N1 N2 D1 D2
2 x b ------------------
3 x c x 1 4 a d (continuous range with same N)
4 x d ==> x 6 7 e f (new range because "5" is missing)
6 x e y 8 10 g h (new range because C changed to "y")
7 x f
8 y g
9 y h
10 y i
SQL Server 是 2005。谢谢。
I need to extract continous ranges from a table based on consecutive numbers (column N) and same "category" these numbers relate to (column C below). Graphically it looks like this:
N C D
--------
1 x a C N1 N2 D1 D2
2 x b ------------------
3 x c x 1 4 a d (continuous range with same N)
4 x d ==> x 6 7 e f (new range because "5" is missing)
6 x e y 8 10 g h (new range because C changed to "y")
7 x f
8 y g
9 y h
10 y i
SQL Server is 2005. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
结果:
Results:
RANK 函数比 ROW_NUMBER 更安全,以防任何 N 值重复,如下例所示:
Result,它正确地承受了重复的 4 和 10:
The RANK function is a safer bet than ROW_NUMBER, in case any N values are duplicated, as in the following example:
Result, which correctly withstands the duplicated 4 and 10:
使用这个答案作为起始点,我最终得到以下结果:
Using this answer as a starting point, I ended up with the following:
写一个存储过程。它将创建并填充一个包含 C、N1、N2、D1 和 D2 列的临时表。
请告诉我您是否需要代码示例。
Write a stored procedure. It will create and fill a temporary table witch will contain C, N1, N2, D1 and D2 columns.
Tell me if you need a code example.