sql - 使用唯一编号的行之间的关系
问题描述
我正在尝试创建 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 中有这个选项吗?
解决方案
与其他评论和答案不同,我看不出序列在这里有什么用处。如果你需要一个选择,这个查询应该可以工作。
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
推荐阅读
- gitlab-ci - 为什么我找不到 Gitlab 缓存目录?
- javascript - Laravel + Vue - 将多维 PHP 数组传递给 vue 组件
- typescript - 为什么打字稿编译器不喜欢铸造?
- python - 通过按下 tkinter 中的按钮向文本小部件键入字母
- python - Pandas:对于数据框中的每个子集,将列中的值设置为等于该列子集的最大值
- node.js - 通过双击 bash 文件在 Ubuntu 中运行 bash 脚本(其中包含一些 npm 命令)会遇到 `npm: command not found` 错误
- wordpress - 无法在 wordpress 中找到 CSS。这里有懂WordPress的人吗?
- reactjs - MUI makeStyles 设置多种样式的道具和逻辑
- c# - 问题显示不正确 - 当前上下文中不存在该名称
- python-3.x - Why can't get the page source with headless browser using selenium?