【问题标题】:Combine month and year from jsonb data PostgreSQL 11.5结合来自 jsonb 数据 PostgreSQL 11.5 的月份和年份
【发布时间】:2021-12-19 17:48:27
【问题描述】:

我的 PostgreSQL 11.5 与此 jsonb 数据类似:

[{"name":"$.publishedMonth", "value":"04"},{"name":"$.publishedYear","value":"1972"}]
[{"name":"$.publishedMonth", "value":"07"},{"name":"$.publishedYear","value":"2020"}]

我想要的结果是:

id publishedMonthYear
1 04-1972
2 07-2020
SELECT b.field_value AS publishedMonthYear, COUNT(*)
  FROM (SELECT *
          FROM (SELECT (jsonb_array_elements(result) ::jsonb) - >> 'name' field_name,
                       (jsonb_array_elements(result) ::jsonb) - >> 'value' field_value,
                  FROM books
                 WHERE bookstore_id = '3') a
         WHERE a.field_name in ('$.publishedMonth', '$.publishedYear')) b
 GROUP BY b.field_value

提前感谢您的任何帮助

【问题讨论】:

    标签: sql postgresql jsonb


    【解决方案1】:

    示例表和数据结构:dbfiddle

    select id, string_agg(value - >> 'value', '-' order by value - >> 'name')
      from book b
     cross join jsonb_array_elements(b.result ::jsonb) e
     group by id
    having array_agg(value - >> 'name'
     order by value - >> 'name') = '{$.publishedMonth,$.publishedYear}'
    

    【讨论】:

      【解决方案2】:

      包含由表booksid 列聚合到JSONB_ARRAY_ELEMENTS() 而没有子查询的查询就足够了,例如

      SELECT id, STRING_AGG(j ->> 'value', '-' ORDER BY j ->> 'name') AS "publishedMonthYear"
        FROM books,
             JSONB_ARRAY_ELEMENTS(result) AS arr(j)
       WHERE bookstore_id = 3
         AND j ->> 'name' IN ('$.publishedMonth','$.publishedYear')
       GROUP BY id
      

      考虑按j ->> 'name' 排序,这将按字母顺序提取所需的值($.publishedMonth$.publishedYear)。

      Demo

      如果需要计算串联的“publishedMonthYear”值,则考虑使用子查询(如评论中所述)

      SELECT "publishedMonthYear", COUNT(*)
        FROM
        ( SELECT STRING_AGG(j ->> 'value', '-' ORDER BY j ->> 'name') AS "publishedMonthYear"
            FROM books,
                 JSONB_ARRAY_ELEMENTS(result) AS arr(j)
           WHERE bookstore_id = 3
             AND j ->> 'name' IN ('$.publishedMonth','$.publishedYear')
           GROUP BY id ) AS b
       GROUP BY "publishedMonthYear"  
      

      Demo

      【讨论】:

      • 感谢您的解决方案,我只想提取 $.publishedMonth 和 $.publishedYear 的值,因为我的 jsonb 中还有其他数据。
      • ,我只想让 j 成为 $.publishedMonth 和 $.publishedYear。因为解决方案还提供了我不想要的电子邮件地址和注释。感谢您的帮助!
      • OK @Ina ,然后需要通过将 AND j ->> 'name' IN ('$.publishedMonth','$.publishedYear') 添加到 WHERE 条件来限制结果。问题已编辑。您可以查看其中的新演示。
      • 然后您可以将当前查询转换为子查询,如this demo@Ina
      • 感激不尽 :D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 2016-06-25
      • 1970-01-01
      相关资源
      最近更新 更多