sql - SQL根据多列添加位置
问题描述
我有一个要在其中添加位置列的表。我需要为表中已有的所有行添加一个编号位置。编号取决于行之间相互匹配的 4 列。例如
id| name| fax | cart| area |
1| jim | 1 | 4 | 1 |
2| jim | 1 | 4 | 1 |
3| jim | 2 | 4 | 1 |
4| jim | 2 | 4 | 1 |
5| bob | 1 | 4 | 1 |
6| bob | 1 | 4 | 1 |
7| bob | 2 | 5 | 1 |
8| bob | 2 | 5 | 2 |
9| bob | 2 | 5 | 2 |
10| bob | 2 | 5 | 2 |
would result with
id| name| fax | cart| area | position
1| jim | 1 | 4 | 1 | 1
2| jim | 1 | 4 | 1 | 2
3| jim | 2 | 4 | 1 | 1
4| jim | 2 | 4 | 1 | 2
5| bob | 1 | 4 | 1 | 1
6| bob | 1 | 4 | 1 | 2
7| bob | 2 | 5 | 1 | 1
8| bob | 2 | 5 | 2 | 1
9| bob | 2 | 5 | 2 | 2
10| bob | 2 | 5 | 2 | 3
我需要一个 sql 查询来遍历表并添加位置。
解决方案
使用row_number()
:
select
t.*,
row_number() over(partition by name, fax, cart, area order by id) position
from mytable t
如果您想要update
查询:
update mytable as t
set position = rn
from (
select id, row_number() over(partition by name, fax, cart, area order by id) rn
from mytable
) x
where x.id = t.id
推荐阅读
- php - 当 POST 的输入值包含单词“选择器”时,远程服务器 Laravel 安装不允许我的 POST 请求数据通过
- apache-flink - 集群节点上的 Flink 作业分布
- windows - 树莓派 3 +Windows IOT Core UART
- php - 如何在 PHP/Laravel 中发送包含破折号(“-”)的 JSON 数据
- vba - Excel VBA 从文件夹中的文件更新主列表
- python - 使用 for 循环格式化数字模式
- javascript - 使用 await 作为参数
- javascript - 当其他视图发生更改时如何更新视图
- c++ - 模板堆栈对象数组;句法
- html - 将背景应用于 flex 子项无法正常工作