【问题标题】:Count not null json key->values in postgres table在 postgres 表中计算不为空的 json 键-> 值
【发布时间】: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": {

  }
}

【问题讨论】:

    标签: sql laravel postgresql


    【解决方案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);
    

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

    【讨论】:

    • 谢谢贾斯宾德。真的很有帮助。
    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多