(免责声明:到目前为止,我对SQL还缺乏经验。)
标题上已经写了。我想将整个表存储为数组元素。所以myarray[1]是表,myarray[2]是另一个表。表的宽度和属性(列名)相同,但记录(行)的数量不同。
也许这不可能仅仅在PostgreSQL中实现,但是应该使用Python来访问PostgreSQL数据库。
所以,PosgreSQL数组不能是“table”类型,也不能是复合类型?
如。
我有一个至少有两个属性(列)和多个记录(行)的关系(表)。真正的表有几十个col和数千行。大大简化:
CREATE TABLE data_orig (category integer, date adate, ...);
INSERT INTO data_orig VALUES (1, 2016-02-28, ...);
INSERT INTO data_orig VALUES (1, 2016-02-29, ...);
-- and so on
INSERT INTO data_orig VALUES (2, 2016-02-28, ...);
INSERT INTO data_orig VALUES (2, 2016-02-29, ...);
INSERT INTO data_orig VALUES (2, 2016-02-27, ...);
--and so on, categories 3 - N
我想要一个数组,其中数组元素是查询的结果。
CREATE TYPE mytype AS (
category int,
adate date);
--关于数组定义的伪代码:
定义myarray mytype[];
我想要一个循环,在这个循环中,原始数据表从最近的日期修剪到最早的日期。事先我不知道某个类别有多少个日期。因此,我可能会有2个或10个或N个表,因此数组大小为2、10或N。
-- Make a copy of the original..
CREATE TEMP TABLE data_temp1 AS
SELECT category,adate FROM data_orig;
-- LOOP would be start here.
-- Get the lines with the latest dates.
CREATE TEMP TABLE data_temp2 AS
(SELECT category, max(adate) AS adate
FROM data_temp1 GROUP BY category);
-- Store the result to array.
**myarray[1] = data_temp2;**
--
-- Substract the last result from the working copy.
CREATE TEMP TABLE data_temp3 AS
(SELECT * FROM data_temp1 EXCEPT SELECT * FROM data_temp2);
DROP TABLE data_temp1;
-- Copy the working copy to data_temp1:
CREATE TEMP TABLE data_temp1 AS (SELECT * FROM data_temp3);
DROP TABLE data_temp2;
-- Get the next recent dates:
CREATE TEMP TABLE data_temp2 AS
(SELECT category, max(adate) AS adate
FROM data_temp1 GROUP BY category);
-- Now again, I want to store this data_temp2 table to the array:
**myarray[2] = data_temp2;**
-- And once again subtract the result data_temp2 from the data_temp1
-- and then repeat, until all rows are inserted in the array of tables
这肯定不是最有效的方法,因为只为了临时使用而多次复制大表,但最终的结果应该是N个表中的最新日期减少。然后对数组中的这些表、更宽的数据源表和其他表执行更多的关系“左连接”,因此需要将它们存储在某个地方。
最佳答案
你可以试试这样的方法:
SELECT category, adate, row_number() OVER (PARTITION BY category ORDER BY adate DESC) as rn
FROM data_orig
这将给每一行一个数字:“1”表示类别中的最新行,“2”表示第二个最新行,以此类推。像这样的:
1, 2016-02-28, 2, ...
1, 2016-02-29, 1, ...
2, 2016-02-28, 2, ...
2, 2016-02-29, 1, ...
2, 2016-02-27, 3, ...
您可以使用这个
SELECT
作为大型SELECT
中的子查询来构建它。顺便说一句,不要试图在关系数据库中的
ARRAY
中放置某些内容。通常这不是你应该做的事。数组属于Java和Python等编程语言,而不是SQL。这条规则的例外情况很少见。关于sql - 是否可以将PostgreSQL(多行)查询结果存储到数组元素中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35709423/