2

我有一张这样的桌子:

+------+-------+
|ID    | value |
+------+-------+
| 1    | 150   |
| 2    |       |
| 3    |       |
| 4    |       |
| 5    | 530   |
| 6    | 950   |
| 7    | 651   |
+-------+------+

我想复制最后 3 个值,最后我的表格将如下所示:

+------+-------+
|ID    | value |
+------+-------+
| 1    | 150   |
| 2    | 530   |
| 3    | 950   |
| 4    | 651   |
| 5    | 530   |
| 6    | 950   |
| 7    | 651   |
+-------+------+

是否可以?

4

3 回答 3

8

使用自加入

UPDATE mytable m
SET    value = m0.value
FROM   mytable m0
WHERE  m.id = (m0.id - 3)   -- define offset
AND    m.id BETWEEN 2 AND 4 -- define range to be affected
AND    m.value IS NULL;     -- make sure only NULL values are updated

如果 ID 空间有间隙,请使用 windows 功能row_number()获取无间隙 ID 以使用。我在 CTE 中这样做,因为我将重复使用该表两次以进行自联接:

WITH x AS (
   SELECT *, row_number() OVER (ORDER BY ID) AS rn
   FROM   mytable
   )
UPDATE mytable m
SET    value = y.value
FROM   x
JOIN   x AS y ON x.rn = (y.rn - 4567)   -- JOIN CTE x AS y with an offset
WHERE  x.id = m.id                      -- JOIN CTE x to original
AND    m.id BETWEEN 1235 AND 3455
AND    m.value IS NULL;

您需要 PostgreSQL 9.1 或更高版本来修改数据 CTE

于 2012-11-22T01:26:44.487 回答
0

对于像这样的临时更新,可能没有比三个简单的更新语句更好的方法了:

UPDATE mytable SET value = 530 WHERE id = 2;
UPDATE mytable SET value = 950 WHERE id = 3;
UPDATE mytable SET value = 651 WHERE id = 4;

问题是,这是仅适用于该确切数据的临时更新,还是您希望为该表中的所有可能数据实施的一般更新规则的情况?如果是这样,那么我们需要更多细节。

于 2012-11-22T01:00:34.887 回答
0

硬编码3出现两次,将被您想要的任意多行替换。它假定最后的3记录实际上具有值。它采用这些值并将它们按顺序应用于具有空值的记录集。

update a
  set value = x.value
  from (

        select nullRows.id, lastRows.value

          from ( select id, value
                       ,(row_number() over(order by id) - 1) % 3 + 1 AS key
                   from ( select id, value
                            from a
                            order by id desc
                            limit 3
                        ) x
                   order by 1

               ) AS lastRows

              ,( select id
                       ,(row_number() over(order by id) - 1) % 3 + 1 AS key
                   from a
                   where value is null
                   order by id

               ) AS nullRows

         where lastRows.key = nullRows.key

      ) x

where a.id = x.id
于 2012-11-22T01:50:18.510 回答