sql-server - 分组连续表数据

标签 sql-server

表格数据

start   end   status
1000    1002    Y
1003    1020    Y
1021    1022    N
1023    1030    Y
1031    1040    Y
1041    1050    Y
1051    1052    N
1053    1100    Y

我想按如下方式对查询结果进行GROUP

start   end   status
1000    1020    Y
1021    1022    N
1023    1050    Y
1051    1052    N
1053    1100    Y

我尝试使用 CTE 递归,但它在大约 37500 次迭代后达到最大值。该表有数十万个元组。

最佳答案

不久前我在这个网站上找到了类似的解决方案。但是没有保存链接。归功于那个人。无论如何,这里有一个 sqlfiddle 来获得你想要的结果,使用未知人的解决方案......

http://sqlfiddle.com/#!18/3e6b1/12/0

它基本上涉及到多次自连接和自检查以获得我们想要的结果。

代码如下:

create table tab1(
  id int identity(1,1) not null,
  startn int not null,
  endn int not null,
  status char(1)
);

insert into tab1(
  startn,
  endn,
  status
)
values
(1000,    1002,    'Y'),
(1003,    1020,    'Y'),
(1021,    1022,    'N'),
(1023,    1030,    'Y'),
(1031,    1040,    'Y'),
(1041,    1050,    'Y'),
(1051,    1052,    'N'),
(1053,    1100,    'Y')
;

设置

select
    t1.startn,
    min(t2.endn) as endn,
    t1.status
from tab1 as t1
join tab1 as t2
    on t1.startn <= t2.startn
    and t1.status = t2.status
    and not exists(
        select
            1
        from tab1 as t3
        where
           t2.endn + 1 >= t3.startn
           and t2.endn < t3.endn
           and t2.status = t3.status
    )
where
    not exists(
        select
            1
        from tab1 as t4
        where
            t1.startn > t4.startn
            and t1.startn <= t4.endn + 1
            and t1.status = t4.status
 )
group by t1.startn, t1.status

查询

关于sql-server - 分组连续表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48411640/

相关文章:

c++ - 将 Visual Studio C++ 控制台应用程序连接到 Microsoft SQL Server 时如何修复 “SQL Server does not exist or access denied.”

mysql - MAX(Date) 给出空结果

sql - 如何减少sql server查询时间

sql - SQL Server 2008 中的拆分函数

php - 修复 SQL 和循环以自动将数据放入 CGridView

sql - SQL Server 中的子查询求和

sql-server - 在 SQL Server 2008 R2 中开始调试时发生错误,错误 HRESULT E_FAIL 已从对 COM 组件的调用返回。 (mscorlib)

python - Python 中的散列

sql - 获取 SQL Server 2008 R2 中列的最后两个非空值

c# - 如何使用存储过程只拆分一行值并插入到多列中,参数值来自C#