PostgreSQL 常用函数(持续更新)

基础知识

SQL语句的执行顺序:FROM、WHERE、GROUP BY、HAVING、SELECT、ORDER BY、LIMIT
圆括号 > and > or

concat_ws(分隔符,value1, value2...):几个值合并成一条
string_agg([distinct] 字段, 分隔符):多行聚合成一个字段
to_char(日期, 日期格式):日期转换为指定格式字符串
to_date(日期, 日期格式):字符串转换为指定格式日期

UNION 和 UNION all 的区别:前者

and 和 or 的混合使用

-- 先执行B = 'b'  and C = 'c' ,再加上A = 'a'的并集
where A = 'a' or B = 'b' and C = 'c' 

-- 等同于A = 'a' and B = 'b' 和 A = 'a' and C = 'c'的并集
where A = 'a' or ( B = 'b' and C = 'c' )

HAVING

GROUP BY id_card HAVING count(*) >1

空字符串和null
一般过滤掉空最好是 A is not null and A <> ''

常用sql

With用法

作为临时表,把复杂sql简单化
-- 方式一
with t1 as (
	select a, b, c from table1 where ...
	group by ...
	union all
	select a, b, c from table2 where ...
	group by ...
)
select a, b, c from a where ...
group by ...

方式二
with t1 as (
	select a, b, c from table1 where ...
	group by ...
), 
with t2 as (
	select a, b, c from a where ...
	group by ...
)
select ... from t1, t2 where ...

with递归查询

with RECURSIVE t1 as (
	select * from table1 where id = ''
	union all
	select t2.* from table1 t2, t1 where t2.parent_id = t1.id
)
select * from t1 
order by id

case when用法

  1. 作用于查询字段,最好字段少
  2. 作用于分组统计
  3. 作用于排序
-- 修改查询结果
select 
	case
		when A = 'a' then 'aa'
		when A = 'b' then 'bb'
		when A <> '' then A
	end A1,
	B
from table1
where ...

-- 分组
select 
	case
		when A = 'a' then 'aa'
		when A = 'b' then 'bb'
	end A1,
	B, count(1)
from table1
where ...
group by B, 
case
	when A = 'a' then 'aa'
	when A = 'b' then 'bb'
end

-- 排序
select A, B
from table1
where ...
order by 
case 
	when A like 'a%' then 1
	when A like 'b%' then 2
end, A asc

row_number() over

row_number() over(partition by 分组列 order by 排序列 desc)
用处:对查询结果进行排序
执行顺序:over()里头的分组以及排序的执行晚于 where 、group by、 order by 的执行

-- 获取分组后的row值作为条件,得出A, B分组后的第一位,实际未group by
select * from (
	select A, B, 
		row_number() over(partition by A, B order by C desc) tmp
	from table1
	where ...
)t where tmp = '1'
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值