首页 > 解决方案 > 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 查询来遍历表并添加位置。

标签: sqlpostgresqlsql-updatewindow-functions

解决方案


使用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

推荐阅读