我有一个名为'receipts'的表格,其中包含以下四个值:
id // serial
payments // jsonb e.g. '[{'method':'card', 'amount':100.00},{'method':'cash', 'amount':150.00}]'
total_price // decimal
status // enum ['confirmed', 'pending']
我想要一个可以更新payments
的查询,并将payments
与total_price
的总和进行比较。如果相同,请将status
更新为“已确认”,否则请将status
更新为“待定”。但是,我无法找到一种方法来获得付款总额并与total_price进行比较。
我认为代码看起来像这样:
UPDATE
receipts
SET
payments = receipts.payments::jsonb || '[{"method":"cash","amount": 50.00}]'::jsonb,
status = (
CASE WHEN
//here to get the sum of exist payments' amount + 50.00 = receipts.total
THEN
'confirmed'
ELSE
'pending'
END
)
WHERE
id = 1
RETURNING
id,
payments,
total_price,
status
答案 0 :(得分:1)
我创建的结构有点接近:
t=# select * from so14;
i | j | st
---+------------------------------------------------------------------------------+----
1 | [{"amount": 30.00, "method": "card"}, {"amount": 11.00, "method": "cash"}] |
2 | [{"amount": 100.00, "method": "card"}, {"amount": 150.00, "method": "cash"}] |
(2 rows)
和这里的聚合示例有点紧密的声明:
t=# with a as (select i,st,(jsonb_array_elements(j)->>'amount')::float f from so14)
, ag as (select i, st, sum(f) from a group by i, st)
update so14 set st = sum
from ag where ag.i = so14.i
returning so14.*;
i | j | st
---+------------------------------------------------------------------------------+-----
1 | [{"amount": 30.00, "method": "card"}, {"amount": 11.00, "method": "cash"}] | 41
2 | [{"amount": 100.00, "method": "card"}, {"amount": 150.00, "method": "cash"}] | 250
(2 rows)
UPDATE 2