首页 > 解决方案 > 使用唯一编号的行之间的关系

问题描述

我正在尝试创建 4 行之间的关系。我需要这个让行有一个唯一的数字。同样在我的下一个插入中,不再给出相同的数字。

例子

ID   Name    uniqueNumber
-------------------------
 1   test1       1
 2   test2       1
 3   test3       1
 4   test4       1
 5   test1       5
 6   test2       5
 7   test3       5
 8   test4       5

我需要一些如何在同一范围内创建行之间的关系。

我想知道我是否可以使用第一个插入行 ID,并在接下来的 3 中使用它。SQL Server 中有这个选项吗?

标签: sqlsql-servertsqlsql-server-2012

解决方案


与其他评论和答案不同,我看不出序列在这里有什么用处。如果你需要一个选择,这个查询应该可以工作。

select 
    ID,
    Name,   
    case when ID % 4 = 0 then ID -3 else (ID - ID % 4) + 1 end as UniqueNumber
from YourTable

或者您可以稍后使用以下查询更新您的表。

update YourTable
set UniqueNumber = case when ID % 4 = 0 then ID -3 else (ID - ID % 4) + 1 end

这会产生这样的输出。

1   test1   1
2   test2   1
3   test3   1
4   test4   1
5   test1   5
6   test2   5
7   test3   5
8   test4   5
9   test1   9
10  test2   9
11  test3   9
12  test4   9
13  test1   13
14  test2   13
15  test3   13
16  test4   13

推荐阅读