1

我是 SQL 的新手,我知道以下问题很受欢迎,但任何建议的解决方案都对我没有帮助。所以,我有一张桌子

ratingId | userId
1        | 1
2        | 2
NULL     | 3
NULL     | 4

现在我想为每一行设置 '3'、'4' 等而不是 NULL ratingId = NULL,这意味着最后一个 NOT NULL 值的 MAX 值 + 1

我用过很多方法,但最流行的是max()

我目前的代码是

SELECT
    COALESCE(rating.id, max(rating.id)) AS id,

但它不起作用:(我仍然有NULL值。有什么建议吗?

4

2 回答 2

1

这是做你想做的吗?

select coalesce(ratingId,
                coalesce(max(ratingId) over (), 0) +
                         count(*) filter (where ratingId is null) over (order by userid)
               ) as imputed_ratingId

一个等效的措辞是:

select coalesce(ratingId,
                coalesce(max(ratingId) over (), 0) +
                         row_number() over (partition by ratingId order by userid)
               ) as imputed_ratingId

ratingId这些为它所在的行提供了唯一性NULL,其增量值超过了先前的最大值。

于 2021-03-10T17:07:58.887 回答
0

我急着回答。NULL 替换为 64,但应从 61 开始。

ratingId | userId
1        | 1
2        | 2
.........|.......
60       | 60
64       | 61 // these row should have ratingId: 61 instead of NULL
64       | 62 // these row should have ratingId: 62 instead of NULL

这是一个原始 SQL

SELECT
    coalesce(r.id,
        coalesce(max(r.id) over (), 0) +
                 count(*) filter (where r.id is null) over (order by r.Id)
       ) as id,
    r2.seqnum AS position,
    coalesce(r3.avg, 0) AS avg,
    r3."avgPosition",
    u.id AS "userId"
FROM ("user" u
      CROSS JOIN "userRole" ur
      LEFT JOIN rating r
      JOIN (SELECT
            r2_1.id,
            r2_1."userId",
            r2_1."userRoleId",
            r2_1."performerRatingGroupId",
            r2_1.value,
            row_number() OVER (PARTITION BY r2_1."userRoleId", r2_1."performerRatingGroupId" ORDER BY r2_1.value DESC) AS seqnum
        FROM rating r2_1
      ) r2 ON ((r2.id = r.id))
      JOIN (SELECT
        r3_1.id,
        r3_2.avg,
        dense_rank() OVER (ORDER BY r3_2.avg) AS "avgPosition"
      FROM
        (rating r3_1
          JOIN (SELECT
              rating.id,
              round(avg(rating.value) OVER (PARTITION BY rating."userId" ORDER BY rating."userId")) AS avg
            FROM rating
          ) r3_2 ON ((r3_1.id = r3_2.id))
        ) 
    ) r3 ON ((r3.id = r.id))
    ON u.id = r."userId" AND ur.id = r."userRoleId"
   )
GROUP BY
  r.id,
  r2.seqnum,
  r3.avg,
  r3."avgPosition",
  u.id
于 2021-03-11T08:32:24.753 回答