SQL在行中查找连续数字

问题描述 投票:-2回答:1

我有一个返回显示的查询。

enter image description here

如果是序列,我需要列出最小和最大数字的行。这应该导致以下输出:请帮忙,我的英语不好。谢谢

enter image description here

sql
1个回答
1
投票

您可以使用交叉应用来查找最大和最小行,并使用dense_rank对序列进行分组。

SQL更新感谢Tony简化我的交叉申请;)

declare @myt table (id int,number bigint, tip int, kalaf int)

insert into @myt
values
(971545701,4110897922,411,41108979),
(971578550,6131339133,613,61313391),
(971578992,6131339402,613,61313394),
(971578993,6131339403,613,61313394),
(971578994,6131339404,613,61313394),
(971579095,6131339627,613,61313396),
(971579100,6131339632,613,61313396),
(971579102,6131339634,613,61313396);

WITH T
AS (
    SELECT *
        ,DENSE_RANK() OVER (
            ORDER BY ID
            ) - ID AS Grp
    FROM @myt
    )
    ,test
AS (
    SELECT MIN(ID) AS RangeStart
        ,MAX(ID) AS RangeEnd
        ,MIN(number) AS minNum
        ,MAX(number) AS maxNum
    FROM T
    GROUP BY Grp
    )
SELECT t.RangeStart AS ID
    ,t.minNum
    ,t.maxNum
    ,f.tip
    ,f.kalaf
FROM test t
INNER JOIN @myt f ON t.RangeStart = f.id
Order by ID

结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.