小编pym*_*kin的帖子

按 JSONB 数组内的唯一值分组

考虑以下表结构:

CREATE TABLE residences (id int, price int, categories jsonb);

INSERT INTO residences VALUES
  (1, 3, '["monkeys", "hamsters", "foxes"]'),
  (2, 5, '["monkeys", "hamsters", "foxes", "foxes"]'),
  (3, 7, '[]'),
  (4, 11, '["turtles"]');

SELECT * FROM residences;

 id | price |                categories
----+-------+-------------------------------------------
  1 |     3 | ["monkeys", "hamsters", "foxes"]
  2 |     5 | ["monkeys", "hamsters", "foxes", "foxes"]
  3 |     7 | []
  4 |    11 | ["turtles"]
Run Code Online (Sandbox Code Playgroud)

现在我想知道每个类别有多少套住宅,以及它们的价格总和。我发现的唯一方法是使用子查询:

SELECT category, SUM(price), COUNT(*) AS residences_no
FROM
  residences a,
  (
    SELECT DISTINCT(jsonb_array_elements(categories)) AS …
Run Code Online (Sandbox Code Playgroud)

postgresql aggregate-functions jsonb

4
推荐指数
1
解决办法
2436
查看次数

标签 统计

aggregate-functions ×1

jsonb ×1

postgresql ×1