在 postgres 表中计算不为空的 json 键-> 值

Posted

技术标签:

【中文标题】在 postgres 表中计算不为空的 json 键-> 值【英文标题】:Count not null json key->values in postgres table 【发布时间】:2020-06-21 02:14:20 【问题描述】:

我有一个带有字段要求(json 字段)的 postgres 表。我需要计算 json 中的非空键。最好的方法是什么?目前我是这样查询的

select COALESCE(t_count,0) + COALESCE(p_count,0) as total_count from (select
CASE
  WHEN requirements->'FRIDGE_SHELF_SPACE'->'order_frequency' is not null then 1
  ELSE 0
 END as t_count,
CASE
  WHEN requirements->'SUPPLY_CHAIN'->'supply_chain_need' is not null then 1
  ELSE 0
END as p_count
from business_requirements where user_id=3561) as t

仅供参考,整个 json(在需求字段中)看起来像这样


  "FRIDGE_SHELF_SPACE": 
    "order_frequency": 
      "question": "How frequently will you be reordering stock?",
      "answer": "Weekly reordering"
    ,
    "units_per_order": 
      "question": "What is your estimated number of units per order?",
      "answer": "10 - 20"
    
  ,
  "Rational_TAP_LINES": 

  ,
  "PERMANENT_TAP_LINES": 

  ,
  "SUPPLY_CHAIN": 
    "supply_chain_need": 
      "question": "What is your supply chain need?",
      "answer": "Brewing ingredients"
    ,
    "supply_chain_requirements": 
      "question": "Select any of the following requirements (leave blank if not applicable)",
      "answer": [
        "Malt",
        "Yeast"
      ]
    
  ,
  "RESEARCH": 

  

【问题讨论】:

【参考方案1】:

您可以使用 postgres json_each 函数来计算键数:


select count(key) from json_each('
  "FRIDGE_SHELF_SPACE": 
    "order_frequency": 
      "question": "How frequently will you be reordering stock?",
      "answer": "Weekly reordering"
    ,
    "units_per_order": 
      "question": "What is your estimated number of units per order?",
      "answer": "10 - 20"
    
  ,
  "Rational_TAP_LINES": 

  ,
  "PERMANENT_TAP_LINES": 

  ,
  "SUPPLY_CHAIN": 
    "supply_chain_need": 
      "question": "What is your supply chain need?",
      "answer": "Brewing ingredients"
    ,
    "supply_chain_requirements": 
      "question": "Select any of the following requirements (leave blank if not applicable)",
      "answer": [
        "Malt",
        "Yeast"
      ]
    
  ,
  "RESEARCH": 

  
') where exists (select 1 from json_each(value) s);

希望这会对你有所帮助:) 祝你好运

【讨论】:

谢谢贾斯宾德。真的很有帮助。

以上是关于在 postgres 表中计算不为空的 json 键-> 值的主要内容,如果未能解决你的问题,请参考以下文章

与从 2 个不为空的表中获取数据相关的数据库查询

选择性过滤列值不为空的行 PostgreSQL

选择字段不为空的数据

Excel filter函数怎么提取数值大于0切不为空的行?

JQ选择值包含字符串且值不为空的对象

对 laravel 的查询以从“已填充”且不为空的 db 行中获取百分比