gpt4 book ai didi

sql - 递归 SQL 语句 (Postgresql) - 简化版

转载 作者:行者123 更新时间:2023-11-29 12:38:37 25 4
gpt4 key购买 nike

这是针对此处发布的更复杂问题的简化问题:

Recursive SQL statement (PostgreSQL 9.1.4)

简化问题

假设您将上三角矩阵存储在 3 列(RowIndex、ColumnIndex、MatrixValue)中:

   ColumnIndex       
1 2 3 4 5
1 2 2 3 3 4
2 4 4 5 6 X
3 3 2 2 X X
4 2 1 X X X
5 1 X X X X

X 值将使用以下算法计算:

M[i,j] = (M[i-1,j]+M[i,j-1])/2
(i= rows, j = columns, M=matrix)

Example:
M[3,4] = (M[2,4]+M[3,3])/2
M[3,5] = (m[2,5]+M[3,4])/2

完整的要求结果是:

   ColumnIndex       
1 2 3 4 5
1 2 2 3 3 4
2 4 4 5 6 5
3 3 2 2 4 4.5
4 2 1 1.5 2.75 3.625
5 1 1 1.25 2.00 2.8125

示例数据:

create table matrix_data (
RowIndex integer,
ColumnIndex integer,
MatrixValue numeric);

insert into matrix_data values (1,1,2);
insert into matrix_data values (1,2,2);
insert into matrix_data values (1,3,3);
insert into matrix_data values (1,4,3);
insert into matrix_data values (1,5,4);
insert into matrix_data values (2,1,4);
insert into matrix_data values (2,2,4);
insert into matrix_data values (2,3,5);
insert into matrix_data values (2,4,6);
insert into matrix_data values (3,1,3);
insert into matrix_data values (3,2,2);
insert into matrix_data values (3,3,2);
insert into matrix_data values (4,1,2);
insert into matrix_data values (4,2,1);
insert into matrix_data values (5,1,1);

这可以做到吗?

最佳答案

测试设置:

CREATE TEMP TABLE matrix (
rowindex integer,
columnindex integer,
matrixvalue numeric);

INSERT INTO matrix VALUES
(1,1,2),(1,2,2),(1,3,3),(1,4,3),(1,5,4)
,(2,1,4),(2,2,4),(2,3,5),(2,4,6)
,(3,1,3),(3,2,2),(3,3,2)
,(4,1,2),(4,2,1)
,(5,1,1);

使用 DO 在循环中运行 INSERT:

DO $$
BEGIN

FOR i IN 2 .. 5 LOOP
FOR j IN 7-i .. 5 LOOP
INSERT INTO matrix
VALUES (i,j, (
SELECT sum(matrixvalue)/2
FROM matrix
WHERE (rowindex, columnindex) IN ((i-1, j),(i, j-1))
));
END LOOP;
END LOOP;

END;
$$

查看结果:

SELECT * FROM matrix order BY 1,2;

关于sql - 递归 SQL 语句 (Postgresql) - 简化版,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11563809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com