在 PostgreSQL 中扩展 json 数组以生成分析
Expanding jsob array in PostgreSQL to produce analytics
假设我们有以下 table 在 PostgreSQL 上使用 jsonb
:
create table writer
(
"firstName" varchar,
"surName" varchar,
books jsonb
);
并提供以下数据:
INSERT INTO public.writer ("firstName", "surName", books) VALUES ('William', 'Shakespeare', '[{"name": "Hamlet"}, {"name": "Romeo and Juliet"}]');
INSERT INTO public.writer ("firstName", "surName", books) VALUES ('Agatha', 'Christie', '[{"name": "Hercule Poirot"}, {"name": "Miss Marple"}]');
是否可以像 PowerBI expand 那样将 JSON 数组扩展到 2 列并获得以下结果?
firstName
surName
bookName
William
Shakespeare
Hamlet
William
Shakespeare
Juliet
Agatha
Christie
Hercule Poirot
Agatha
Christie
Miss Marple
而不是
firstName
surName
books
William
Shakespeare
[{"name": "Hamlet"}, {"name": "Romeo and Juliet"}]
Agatha
Christie
[{"name": "Hercule Poirot"}, {"name": "Miss Marple"}]
您可以使用 jsonb_array_elements()
为每个数组元素获取一行:
select w."firstName", w."surName", b.book ->> 'name' as book_name
from writer w
cross join jsonb_array_elements(books) as b(book)
假设我们有以下 table 在 PostgreSQL 上使用 jsonb
:
create table writer
(
"firstName" varchar,
"surName" varchar,
books jsonb
);
并提供以下数据:
INSERT INTO public.writer ("firstName", "surName", books) VALUES ('William', 'Shakespeare', '[{"name": "Hamlet"}, {"name": "Romeo and Juliet"}]');
INSERT INTO public.writer ("firstName", "surName", books) VALUES ('Agatha', 'Christie', '[{"name": "Hercule Poirot"}, {"name": "Miss Marple"}]');
是否可以像 PowerBI expand 那样将 JSON 数组扩展到 2 列并获得以下结果?
firstName | surName | bookName |
---|---|---|
William | Shakespeare | Hamlet |
William | Shakespeare | Juliet |
Agatha | Christie | Hercule Poirot |
Agatha | Christie | Miss Marple |
而不是
firstName | surName | books |
---|---|---|
William | Shakespeare | [{"name": "Hamlet"}, {"name": "Romeo and Juliet"}] |
Agatha | Christie | [{"name": "Hercule Poirot"}, {"name": "Miss Marple"}] |
您可以使用 jsonb_array_elements()
为每个数组元素获取一行:
select w."firstName", w."surName", b.book ->> 'name' as book_name
from writer w
cross join jsonb_array_elements(books) as b(book)