如何从表中不同列的一组数字中识别是否存在连续数字?

时间:2020-06-13 07:29:52

标签: sql sql-server tsql

我正在使用SQL Server 2014,并且有一个表(t1)。摘录如下所示:

Id    n1   n2    n3    n4    n5    n6
-------------------------------------
100   5    10    15    21    22    30
121   1     6    14    31    35    37
126   4     5    22    27    28    38
...

我需要一个新列Consecutive,它将表中的每一行标记为“是”或“否”。

预期输出:

Id    n1   n2    n3    n4    n5    n6  Consecutive
--------------------------------------------------
100   5    10    15    21    22    30      Yes
121   1     6    14    31    35    37      No
126   4     5    22    27    28    38      Yes
...

注意:n1到n6的所有行都按升序排列。

如何使用T-SQL做到这一点?

2 个答案:

答案 0 :(得分:2)

尝试使用case语句。这是demo

select
    *,
    case
        when (n1 + 1 = n2 
        or  n2 + 1 = n3         
        or  n3 + 1 = n4
        or  n4 + 1 = n5
        or  n5 + 1 = n6) then 'Yes'
        else 'No'
    end as consecutive
from myTable

输出:

| Id  | n1  | n2  | n3  | n4  | n5  | n6  | consecutive |
| --- | --- | --- | --- | --- | --- | --- | ----------- |
| 100 | 5   | 10  | 15  | 21  | 22  | 30  | Yes         |
| 121 | 1   | 6   | 14  | 31  | 35  | 37  | No          |
| 126 | 4   | 5   | 22  | 27  | 28  | 38  | Yes         |

答案 1 :(得分:2)

您还可以执行以下操作

SELECT T.*, CASE WHEN 1 IN(N2-N1, N3-N2, N4-N3, N5-N4, N6-N5)
                 THEN 'Yes'
                 ELSE 'No'
            END Consecutive
FROM
(
    VALUES
    (100,   5,    10,    15,    21,    22,    30),
    (121,   1,     6,    14,    31,    35,    37),
    (126,   4,     5,    22,    27,    28,    38)
) T(Id, N1, N2, N3, N4, N5, N6);