SQL Server 查找起始编号和终止编号

g9icjywg  于 2023-01-08  发布在  其他
关注(0)|答案(3)|浏览(168)

我正在寻找使用正确的窗口功能为我的SQL问题。
我有下表,我需要找到连续范围的startend编号。
日志表:

+------------+
| log_id     |
+------------+
| 1          |
| 2          |
| 3          |
| 7          |
| 8          |
| 10         |
+------------+

预期结果:

+------------+--------------+
| start_id   | end_id       |
+------------+--------------+
| 1          | 3            |
| 7          | 8            |
| 10         | 10           |
+------------+--------------+
cgvd09ve

cgvd09ve1#

其思想是减去一个递增值,然后进行合计:

select min(log_id), max(log_id)
from (
    select t.*, row_number() over (order by log_id) as seqnum
    from t
) t
group by (log_id - seqnum)
order by min(log_id);
ql3eal8s

ql3eal8s2#

您可以使用row_number(),尝试以下操作,这里是演示。

select
    min(log_id) as start_id,
    max(log_id) as end_id
from
(
    select
        log_id,
        log_id - row_number() over (order by log_id) as rnk
    from logs
) t
group by
    rnk
euoag5mw

euoag5mw3#

你也可以创建CTE-

With CTE AS(
select log_id,
log_id-row_number() over(order by log_id) as diff from logs)

Select MIN(log_id) as start_id,MAX(log_id) as end_id from CTE group by diff
ORDER by start_id

相关问题