基于PostgreSQL的sql

本文介绍了在PostgreSQL中进行SQL操作的一些实用技巧,包括使用`select * into`进行表备份,日期的格式化,如`to_char`和`to_date`函数,以及数据处理函数如`coalesce`、`round`和`age`。还展示了如何进行更新和插入操作,以及计算年龄的不同方法。此外,文章提到了动态行转列、合并结果集和使用`COALESCE`处理NULL值的方法,以及`CASE WHEN THEN ELSE END`和`ROW_NUMBER() OVER()`的用法。
摘要由CSDN通过智能技术生成

表备份
select * into price_list1708151648 from price_list;


---日期格式化---
to_char(birthdate, 'yyyy-MM-dd')  返回string    'yyyy-MM-dd HH24:mi:ss'
to_date(to_char(birthdate, 'yyyy-MM-dd'),'yyyy-MM-dd')  返回date

----函数----
coalesce(num,0)  num如果是null返回0
round(num,2);   四舍五入保留两位小数
floor(num);     向下取整 (类型不变,double还是double)
age(date1,date2); 返回如:16 years 7 mons 8 days
cast(3.33  as int4)  类型转换,如转为整型,返回3

ROW_NUMBER() OVER()  行号

-----更新----
update war_stqty_lst set unit=a.leastunit from (select b.id,b.leastunit from pub_drug b) a
where war_stqty_lst.unit is null and a.id=war_stqty_lst.drugid

--插入
INSERT into o2o_other_retail_goods (channel,goods_id,retail_id,o2o_spec_id,defprice,_version)
select aa.* from (select 2 channel,b.goodsid goods_id,a.id retail_id,b.o2o_spec_id,b.defprice,1 _version
 from (select id from pub_retail where mt_flag=true and status=1) a,a1_test b) aa

------求年龄------
select id,username,birthdate,(('2017-07-20'-to_date(to_char(birthdate, 'yyyy-MM-dd'),'yyyy-MM-dd'))/365) as age from pub_user;//方法一

SELECT cast(extract(year from age(current_date,birthdate)) as int4) as age from pub_user;//方法二


select (case when a.years=0 and a.mons=0 and a.days=0 then ''
when a.years=0 and a.m

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值