2016-12-13 43 views
0

理想情況下,我希望運行一個查詢,該查詢返回一個表,其中每行是指定表的列名,並且jsonb表對應於該列的表中所有不同值的數組。如何獲取Postgres中單個表中所有列的不同值?

棘手的部分似乎是動態的,我只能指定表格而不是每個單獨的列。

我可以從information_schema.columns檢索相關表的所有列名,但有沒有簡單的方法將它與查詢耦合以檢索每列的所有不同值?

+0

它採取的裂縫和職位的代碼。 – dfundako

回答

2
create table example(id int primary key, str text, val numeric); 
insert into example values 
(1, 'a', 1), 
(2, 'a', 2), 
(3, 'b', 2); 

select key, array_agg(distinct value) 
from example, jsonb_each_text(to_jsonb(example)) 
group by key; 

key | array_agg 
-----+----------- 
id | {1,2,3} 
str | {a,b} 
val | {1,2} 
(3 rows)  

select key, json_agg(distinct value) 
from example, jsonb_each(to_jsonb(example)) 
group by key; 

key | json_agg 
-----+------------ 
id | [1, 2, 3] 
str | ["a", "b"] 
val | [1, 2] 
(3 rows)  
+0

謝謝!這完全按照需要工作,並幫助我理解如何去做這種事情。 –

0

不知道我完全瞭解你,但這似乎做你想要什麼:

select json_build_object(colname, array_agg(distinct val)) 
from the_table 
    cross join lateral json_each_text(row_to_json(the_table)) as j(colname,val) 
group by colname; 
相關問題