Postgresql 如何在 jsonb 中按月份求和(值)并将它们分组?

Postgresql how can I sum(values) and group them by the month within jsonb?

Postgres 查询:

SELECT
  ((data->>'date')) AS time,
  ((data->>'totalAmount')) as values
FROM invoices

输出:

id date total amount
1 2021-01-16 13
2 2021-01-12 52
3 2020-12-17 11
4 2020-12-08 3

Table:

CREATE TABLE invoices (
    id serial NOT NULL PRIMARY KEY,
    data jsonb NOT NULL
);

我尝试按月实现总和(值)的目标:

id date total amount
1 2021-01 65
2 2020-12 14

我知道 postgres 提供:

jsonb 好像不行

您需要将文本值转换为 date 然后您可以,例如使用 to_char() 从中获取月份:

select to_char((data->>'date')::date, 'yyyy-mm') AS month,
       sum((data->>'totalAmount')::int) as values
from invoices
group by to_char((data->>'date')::date, 'yyyy-mm')