You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
3.2 KiB
3.2 KiB
-
批量like
like any (array['%.jpg','%.jpeg'])
-
创建序列
create SEQUENCE id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; alter table kx_hospital ALTER COLUMN id set DEFAULT nextval('_id_seq')
-
获取当前时间绝对秒
select floor(extract(epoch from now()))
-
雪花ID函数
create SEQUENCE table_id_seq START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; CREATE OR REPLACE FUNCTION "public"."snow_next_id"(OUT "result" int8) RETURNS "pg_catalog"."int8" AS $BODY$ DECLARE our_epoch bigint := 1314220021721; seq_id bigint; now_millis bigint; shard_id int := 5; BEGIN seq_id := nextval('table_id_seq') % 1024; SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis; result := (now_millis - our_epoch) << 23; result := result | (shard_id << 10); result := result | (seq_id); END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100
-
count统计过滤及去重
count(distinct(speaker_id||speak_time||content)) FILTER (where t.mark='text') ----- 使用distinct 去重 filter用于过滤
-
PG 操作schema
drop SCHEMA "public" CASCADE --强制删除,包含模式下所有对象(表、函数等) create SCHEMA "public" --创建 alter schema name RENAME TO new_name -- 修改模式名称 alter schema name OWNER TO new_owner -- 修改拥有者
-
获取单位时间间隔时间
-- 获取6个月前时间 select to_char((select now() - interval '6 month'),'yyyy-MM-dd hh24:mi:ss')
-
窗口函数分组统计(根据collect_code分组,并以collect_time 倒序)
select collect_value,row_number() over(PARTITION by collect_code ORDER BY collect_time desc) from nc_data_collect_value_test
-
lead函数获取上一条记录,并计算增量
select create_date,node_value as total,next_day_total,next_day_total::int8-node_value::int8 as increment from ( with a as (SELECT create_date, node_value FROM nc_data_node_value_detail WHERE node_code = '' ORDER BY create_date DESC ) select create_date,node_value,lead(node_value,1) over (ORDER BY create_date) next_day_total FROM a ORDER BY create_date desc) tt
-
lag函数获取下一条记录
select create_date,node_value as total,next_day_total,abs(next_day_total::int8-node_value::int8) as increment from ( with a as (SELECT create_date, node_value FROM nc_data_node_value_detail WHERE node_code = '' ORDER BY create_date DESC ) select create_date,node_value,lag(node_value,1) over (ORDER BY create_date) next_day_total FROM a ORDER BY create_date desc) tt
- 序列生成
# 时间序列
# 例:生成从2021年到2023年
select to_char(generate_series(to_date('2021','yyyy'),to_date('2023','yyyy'),'1 years'),'yyyy')
# 生成今天24小时
select to_char(generate_series(to_timestamp(current_date || ' 00:00:00', 'yyyy-MM-dd HH24:mi:ss'),
to_timestamp(current_date || ' 23:59:59', 'yyyy-MM-dd HH24:mi:ss'), '1 hour'),'yyyy-MM-dd HH24:mi:ss')
- 获取本月第1天和最后一天
select date_trunc('month',current_date),date_trunc('month',current_date)+interval '1 month - 1 day';