根据 postgresql 中的上一行更新数据

问题描述

  CREATE TABLE xyz (name text,cols int,rows int,minitemcols int,x int,y int,rn int);
  INSERT INTO xyz ("widgetName",cols,"rows","minItemCols",x,y,rn) VALUES
     ('A',12,19,8,1),('B',11,NULL,2),('C',5,6,4,3),('D',3,4),('E',5),('F',6),('G',7),('H',8),('I',7,9),('J',9,10)
     ('K',24,11),('L',16,12),('M',13);
-- x
IF (CurrentRow.cols + CurrentRow.x = 12) || (CurrentRow.cols + CurrentRow.x = NextRow.minItemCols) THEN 
    NextRow.x = 0
ELSE IF (CurrentRow.cols + CurrentRow.x < 12) && (CurrentRow.cols + CurrentRow.x >= NextRow.minItemCols)
    NextRow.x = CurrentRow.cols + CurrentRow.x
ELSE IF (CurrentRow.cols + CurrentRow.x < 12)
    NextRow.x = CurrentRow.cols + CurrentRow.x
END IF;    


--y
IF (CurrentRow.cols + CurrentRow.x = 12) THEN 
    NextRow.y = CurrentRow.rows + CurrentRow.y
ELSE IF (CurrentRow.cols + CurrentRow.x < 12)
    NextRow.y = CurrentRow.y
END IF;   
-- Output (providing in insert statements)

INSERT INTO xyz ("widgetName",30,36,42,48,57,81,13);

对于 rn(行号)= 1,x 和 y 始终保持为 0。现在我需要根据上述情况(IF ..ELSE)更新 x 和 y 列的其余部分。如果不更新上一行,我将无法更新下一行。有没有办法在查询中做到这一点

解决方法

您可以对此类查询使用递归 CTE:

WITH RECURSIVE rec(name,col,row,min_item_col,x,y,rn) AS (
    SELECT *
    FROM xyz
    WHERE rn = 1

    UNION ALL

    (
        SELECT next.name,next.cols,next.rows,next.minitemcols,CASE
                   WHEN cur.col + cur.x = 12 THEN 0
                   WHEN cur.col + cur.x = next.minitemcols THEN 0
                   /* this 3rd condition seems pointless given the last one */
                   WHEN cur.col + cur.x < 12 AND cur.x + cur.col >= next.minitemcols THEN cur.col + cur.x
                   WHEN cur.col + cur.x < 12 THEN cur.col + cur.x
               END AS x,CASE
                   WHEN cur.col + cur.x = 12 THEN cur.row + cur.y
                   WHEN cur.col + cur.x < 12 THEN cur.y
               END AS y,next.rn
        FROM rec AS cur
        JOIN xyz AS next
          ON next.rn > cur.rn
        ORDER BY rn
        LIMIT 1
    )
)
UPDATE xyz
SET x = rec.x,y = rec.y
FROM rec
WHERE xyz.rn = rec.rn
;

将表更新为

+----+----+----+-----------+----+----+--+
|name|cols|rows|minitemcols|x   |y   |rn|
+----+----+----+-----------+----+----+--+
|A   |12  |19  |8          |0   |0   |1 |
|B   |12  |11  |12         |0   |19  |2 |
|C   |5   |6   |4          |0   |30  |3 |
|D   |3   |6   |3          |5   |30  |4 |
|E   |4   |6   |3          |8   |30  |5 |
|F   |4   |6   |4          |0   |36  |6 |
|G   |3   |6   |3          |4   |36  |7 |
|H   |5   |6   |5          |7   |36  |8 |
|I   |7   |6   |7          |0   |42  |9 |
|J   |12  |9   |12         |7   |42  |10|
|K   |12  |24  |8          |NULL|NULL|11|
|L   |5   |16  |3          |NULL|NULL|12|
|M   |7   |16  |7          |NULL|NULL|13|
+----+----+----+-----------+----+----+--+

请注意,从“K”行开始,结果与您的示例略有不同。我认为 "row J".x 应该是 7 而不是 0 (来自最后一个 else if 条件),这也会改变其余的行。不过,我认为调整代码以获得您想要的结果应该很容易。