我正在创建一个 PostgreSQL 查询来解决以下场景:
"info_column": {
"attribute1": 10,
"attribute2": 50,
"attribute3": [
{"value": 10, "description": "desc1"},
{"value": 20, "description": "desc2"},
{"value": 30, "description": "desc3"}
],
"attribute4": [
{"value": 40, "description": "desc4"},
{"value": 50, "description": "desc5"},
{"value": 60, "description": "desc6"}
]
}
attribute1
、attribute2
、attribute3
和 attribute4
之和。
attribute1
和 attribute2
,总和将是它们显示为其属性值的数字。value
的总和。 | attribute1| attribute2| attribute3| attribute4
row1| 10| 50| 60| 150
我非常感谢您就此事提供的任何帮助。
Hope below query can help
consider your PostgreSQL table name student_info and field meta_data contain your json then below query can give your expected result
SELECT
(
CASE
WHEN JSON_TYPEOF(meta_data->'info_column'->>'attribute1') = 'array'
THEN (
SELECT SUM(value::integer) AS sum_of_attribute1
FROM (
SELECT json_array_elements_text(meta_data->'info_column'->'attribute1')->>'value' AS value
) attribute1_sum
)
ELSE
(meta_data->'info_column'->>'attribute1')::integer
END
) AS attribute1,
(
CASE
WHEN JSON_TYPEOF(meta_data->'info_column'->>'attribute2') = 'array'
THEN (
SELECT SUM(value::integer) AS sum_of_attribute2
FROM (
SELECT json_array_elements_text(meta_data->'info_column'->'attribute2')->>'value' AS value
) attribute2_sum
)
ELSE
(meta_data->'info_column'->>'attribute2')::integer
END
) AS attribute2,
(
CASE
WHEN JSON_TYPEOF(meta_data->'info_column'->'attribute3') = 'array'
THEN (
SELECT SUM(value::integer) AS sum_of_attribute3
FROM (
SELECT json_array_elements_text(meta_data->'info_column'->'attribute3')->>'value' AS value
) attribute3_sum
)
ELSE
meta_data->'info_column'->>'attribute3'
END
) AS attribute3,
(
CASE
WHEN JSON_TYPEOF(meta_data->'info_column'->'attribute4') = 'array'
THEN (
SELECT SUM(value::integer) AS sum_of_attribute4
FROM (
SELECT json_array_elements_text(meta_data->'info_column'->'attribute4')->>'value' AS value
) attribute4_sum
)
ELSE
meta_data->'info_column'->>'attribute4'
END
) AS attribute4
FROM student_info
WHERE meta_data IS NOT NULL;