我有PostgreSQL 11.5与类似的jsonb数据:
[{"name":"$.publishedTitle", "value":"Code"},{"name":"$.publishedYear","value":"1972"}]
[{"name":"$.publishedTitle", "value":"Test"},{"name":"$.publishedYear","value":"2020"}]
[{"name":"$.publishedTitle", "value":"Code"},{"name":"$.publishedYear","value":"2019"}]
我想要的结果是(一个标题发布了多少次
| 标题|发布年份计数|
| - ------|- ------|
| 代码|第二章|
| 试验|1个|
我已经试过了:
SELECT distinct(b.field_value) AS publishedYearCount, 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 ('$.publishedTitle', '$.publishedYear')) b
GROUP BY b.field_value
1条答案
按热度按时间7eumitmz1#
我知道你想计算每个出版物的不同年份。
您可以在一个横向连接中取消嵌套每个数组,并将年份和标题放在同一行上;那么我们就可以在外部查询中进行聚合和计数: