PostgreSQL常见SQL查询

1.现有表A如下数据, 表字段 Id, member_id,receiver,status,amount,month; receiver字段为JSONB类型

idmember_idreceiverstatusamountmonth
11000{“name”: “张三”, “account”: “13100000000”}122.222022-01
21001{“name”: “李四”, “account”: “13100000001”}211.112022-02
31002{“name”: “王五”, “account”: “13100000002”}333.332022-03

(1) 需要单独列出name,account

SELECT (receiver ->> 'name') name, (receiver ->> 'account') account FROM 表A 

(2) 需要查询name为"张三"的数据

SELECT id,receiver FROM 表A WHERE receiver::JSONB @> '{"name":'张三'}'::jsonb

(3) 需要查询account为"13100000001"的数据

SELECT id,receiver FROM 表A WHERE receiver::JSONB @> '{"account":'13100000001'}'::jsonb

(3) 需要统计其中几个状态的总金额

SELECT COALESCE(SUM(amount) FILTER (WHERE status= 1), 0.00) fristAmount,
       COALESCE(SUM(amount) FILTER (WHERE status= 2), 0.00) twoAmount
FROM 表A

(4) 需要统计某月的总金额

SELECT COALESCE(SUM(amount) FILTER (WHERE month= '2022-01'), 0.00) monthAmount FROM 表A

(5) 表A的member_id建立唯一索引,如做新增或者修改操作

INSET INTO 表A AS aa (member_id, receiver, status, amount, month)
VALUES (#{memberId}, #{receiver,typeHandler=***.JSONHandler},#{status},#{amount},#{month})
ON CONFLICT(member_id)
DO UPDATE SET receiver= #{receiver,typeHandler=***.JSONHandler},
              status = #{status},
              amount= #{amount}
WHERE aa.member_id = #{memberId}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值