将 row_number 添加到最大值

Add row_number to maximum value

这是我的问题的简化版本(我想不出一个在现实生活中有意义的例子)。

假设我有一个 Table 人

Table 人


ID       Name        Number     Category
1        Follett     null       Thriller
2        Rowling     null       Fantasy
3        Martin      80         Fantasy
4        Cage        55         Thriller
5        Baldacci    null       Thriller

现在我想得到以下结果:


ID       Name        Number     Category
1        Follett     56         Thriller
2        Rowling     81         Fantasy
3        Martin      80         Fantasy
4        Cage        55         Thriller
5        Baldacci    57         Thriller
  1. 按类别分组
  2. Select每个类别的最大数值
  3. 将 row_number(按类别划分)添加到该数字并设置新值,(编辑:)但仅适用于之前为空的数字。

我目前的部分(不工作,更多的是为了说明我想做什么,我知道为什么这不可能工作)


UPDATE Person P
SET Number = sub.current + sub.row
FROM (
  SELECT
   Id,
   max(Number) as current,
   (ROW_NUMBER() OVER(PARTITION BY Category)) AS row
  FROM Person
  GROUP BY Category
) as sub
WHERE P.Id = sub.Id

注意:对于一个类别的所有数字都为空的极端情况,max(Number) 应该只是 0,新值应该只是 row_numbers()。

我正在使用 Postgresql。

您可以使用以下方法获取 select 中的值:

select p.*,
       (coalesce(max(number) over (partition by category), 0) +
        row_number() over (partition by category order by number)
       ) as newnumber
from person p;

然后您可以将其放入 update 语句中:

update person
    set number = pp.newnumber
    from (select p.*,
           (coalesce(max(number) over (partition by category), 0) +
            row_number() over (partition by category order by number)
           ) as newnumber
          from person p
         ) pp
    where pp.id = p.id and p.number is null;

注意:如果您尝试创建唯一值,这样做可能行不通。特定类别的序号可能与另一类别的序号冲突。如果这是您想要做的,请提出另一个问题并提供更多详细信息。