我有一个包含三个一维数组的表(还有一个主键和其他几个列,但它们并不重要)。所有这些数组都可以为NULL
。每列中的数组确实经常重叠:许多值位于多个数组中。我现在想要一个查询,它返回一行,其中三个数组是整个数组列的不同值。
像这样创建测试表
DROP TABLE IF EXISTS my_array_test;
CREATE TABLE IF NOT EXISTS my_array_test(id integer, my_txt text[], my_int1 integer[], my_int2 integer[]);
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (1,'{text1,text2}','{1,2}','{21,22}');
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (2,null,'{7,8}','{21,22}');
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (3,'{text2,text4}',null,null);
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (3,null,null,'{17,18}');
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (4,'{text1,text2}','{1,2,3}','{21,22}');
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (5,'{text1,text5}','{1,5}','{21,25}');
INSERT INTO my_array_test(id, my_txt, my_int1, my_int2) VALUES (6,null,null,null);
结果是这样的
select * from my_array_test ;
id | my_txt | my_int1 | my_int2
----+---------------+---------+---------
1 | {text1,text2} | {1,2} | {21,22}
2 | | {7,8} | {21,22}
3 | {text2,text4} | |
3 | | | {17,18}
4 | {text1,text2} | {1,2,3} | {21,22}
5 | {text1,text5} | {1,5} | {21,25}
6 | | |
(7 rows)
预期结果为 {text1,text2,text4,text5},{1,2,7,8,2,5},{21,22,17,18,25}
(数组内的顺序并不重要。)
我尝试的是像这样的多重横向查询:
SELECT
array_agg(DISTINCT t) AS text_array_result,
array_agg(DISTINCT i1) AS integer_array1_result,
array_agg(DISTINCT i2) AS integer_array2_result
FROM
my_array_test,
unnest(my_txt) AS t,
unnest(my_int1) AS i1,
unnest(my_int2) AS i2
但是,这会杀死仅包含 NULL
数组的行中的所有值。
我也尝试过 unnest(COALESCE(my_txt,'{}')) AS t,
等,但没有效果。
最佳答案
您可以使用我描述的自定义聚合 in this post.
select
array_merge_agg(my_txt) AS text_array_result,
array_merge_agg(my_int1) AS integer_array1_result,
array_merge_agg(my_int2) AS integer_array2_result
from
my_array_test;
text_array_result | integer_array1_result | integer_array2_result
---------------------------+-----------------------+-----------------------
{text1,text2,text4,text5} | {1,2,3,5,7,8} | {17,18,21,22,25}
(1 row)
关于sql - 多个不同的数组,其中包含空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570876/