1

我有一张如下表:

id    rank    user
1      1       1
2      1       1
3      1       2
4      2       1
5      2       1

我想rank将给定用户的值分布在 1(或 0)和最大值之间,以便在值之间留出空间。例如,我想传播rankfor user 1,最大值为 100 (在这种情况下),结果应该是:

id    rank    user
1      20      1
2      40      1
3      1       2
4      60      1
5      80      1

我想计算一个increment = maxValue / count(items) + 1,然后对每个新UPDATE的查询进行多次查询increment,但这似乎效率极低。有没有办法做得更好,也许有一个大UPDATE查询,比如:

UPDATE MyTable
SET rank = increment * ??? (?current position? in SELECT * FROM MyTable WHERE user = 1 ORDER BY rank)
WHERE user = 1
4

1 回答 1

2

您可以通过使用 a为用户的每个条目CTE生成一个行号 ( )(按顺序重复排序)以及该用户的行数的计数 ( ),然后设置for该用户是:rnrankidcntrank

rn * 100 / (cnt + 1)

作为查询:

WITH CTE AS (
  SELECT id, user, 
         ROW_NUMBER() OVER (PARTITION BY user ORDER BY rank, id) AS rn,
         COUNT(*) OVER (PARTITION BY user) AS cnt
  FROM MyTable
  WHERE "user" = 1
)
UPDATE MyTable
SET rank = CTE.rn * 100 / (CTE.cnt + 1)
FROM CTE
WHERE MyTable.id = CTE.id

结果表:

id  rank    user
1   20      1
2   40      1
3   1       2
4   60      1
5   80      1

SQLFiddle 上的演示

于 2020-01-07T02:13:21.993 回答