【问题标题】:Expanding jsob array in PostgreSQL to produce analytics在 PostgreSQL 中扩展 json 数组以产生分析
【发布时间】:2022-01-20 11:35:12
【问题描述】:

假设我们在 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"}]

示例数据库:http://sqlfiddle.com/#!17/87ca94/2

【问题讨论】:

  • 旁注:JSON 的架构对我来说看起来相当静态。您应该考虑不要滥用 JSON,而是使用关系方式,例如(查找和/或链接)表和列。

标签: sql postgresql jsonb


【解决方案1】:

您可以使用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)

Online example

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多