欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > PGSQL基本使用

PGSQL基本使用

2025/6/27 23:58:27 来源:https://blog.csdn.net/swg321321/article/details/146238447  浏览:    关键词:PGSQL基本使用

PGSQL基本使用

文章目录

  • PGSQL基本使用
  • 日期转换
    • 长度不够补数
    • 获取上下行
    • 取连续的开始和结束的值


日期转换

格式说明
YYYY
MM
DD
hh2424小时制
mi分钟
ss
-- 日期字符串转指定日期字符串
-- 20250101123000 转为 2025-01-01 12:30:00
select to_char(to_timestamp('20250101123000','YYYYMMDDhh24miss'),'YYYY-MM-DD hh24:mi:ss') as t;

长度不够补数

不足前面补数

-- 得到字符串 '09300000'
select lpad(cast(9300000 as text),8,'0') as t;

不足前面补数

-- 得到字符串 '15300000'
select lpad(cast(153000 as text),8,'0') as t;

获取上下行

获取上一行

-- 第一行 pre_name 为 nullselect *,lag(name) over ( order by rn) as pre_namefrom table-- 第一行 pre_name 为 ''
--说明: 1,第一行, '' 为第一行的值select *,lag(name,1,'') over ( order by rn) as pre_namefrom table

获取下一行

-- 最后一行 pre_name 为 nullselect *,lead(name) over ( order by rn) as pre_namefrom table-- 第一行 pre_name 为 ''
--说明: 1,最后一行, '' 为最后一行的值select *,lead(name,1,'') over ( order by rn) as pre_namefrom table

取连续的开始和结束的值

同一个账户,订单编号需要去除,5,9 。计算订单编号连续

-- 基础数据
with base as (select  1 as order_num, 'A01' as acct_idunion all select  2 as order_num, 'A01' as acct_idunion all select  3 as order_num, 'A02' as acct_idunion all select  4 as order_num, 'A02' as acct_idunion all select  5 as order_num, 'A02' as acct_idunion all select  6 as order_num, 'A02' as acct_idunion all select  7 as order_num, 'A01' as acct_idunion all select  8 as order_num, 'A01' as acct_idunion all select  9 as order_num, 'A01' as acct_idunion all select  10 as order_num, 'A01' as acct_idunion all select  11 as order_num, 'A01' as acct_id),-- 根据acct_id分组,根据order_num排序
base_order as (select *, row_number() over (partition by acct_id order by order_num) as rn from base
),
-- 获取上下行的rn
-- lag(rn,1,null) 表示第一行的 rn值为空
-- lead(rn,1,null) 表示最后一行的 rn值为空
base_rn as (
select *,lag(rn,1,null) over (partition by acct_id order by order_num) as pre_rn,lead(rn,1,null) over (partition by acct_id order by order_num) as next_rn
from base_order
where order_num != 5 and order_num != 9
),
-- 计算acct_id连续的 order_num
base_link as (
select *,case when pre_rn is null or pre_rn + 1 != rn then  order_num else null end as start_order_num, /**连续的开始*/case when next_rn is null or next_rn -1 != rn then order_num else null end as end_order_num, /**连续的结束*/sum(case when pre_rn is null or pre_rn + 1 != rn then 1 else 0 end) over (partition by acct_id order by order_num) as link_cnt /**连续的分为一组*/
from base_rn
)
-- 获取连续的开始订单编号和对应的结束订单编号
select max(start_order_num) as start_order_num,max(end_order_num) as end_order_num, acct_id
from base_link
group by acct_id, link_cnt

得到结果

start_order_numend_order_numacct_id
12A01
34A02
66A02
78A01
1011A01

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词