PgSQL高级

PgSQL高级

SQL执行顺序
(9) SELECT (10) DISTINCT col1,
[OVER()] (6) AGG_FUNC(col2)
(1) FROM table1
(3) JOIN table2
(2) ON table1.col = table2.col
(4) WHERE constraint_expression
(5) GROUP BY col
(7) WITH CUBE|ROLLUP
(8) HAVING constraint_expression
(11) ORDER BY col ASC |DESC
(12) LIMIT count OFFSET count
复制表结构(不复制表注释,其他都复制)
CREATE TABLE emp_copy (LIKE emp including all);
分组聚合

grouping sets扩展 (单个)

select os,device, city ,count(*)
from requests
group by grouping sets((os, device), (city), ());
上述语句等效于如下语句:
select os, device, NULL, count(*)
from requests group by os, device
union all
select NULL, NULL, NULL, count(*)
from requests
union all
select null, null, city, count(*)
from requests group by city;

rollup(嵌套)

select os,device, city ,count(*) from requests 
group by grouping sets((city), ROLLUP(os, device));
上述语句等效于如下语句:
select os,device, city ,count(*) from requests 
group by grouping sets((city), (os), (os, device), ());

cube(组合)

select os,device, city, count(*)
from requests 
group by cube (os, device, city);
上述语句等效于如下语句:
select os,device, city, count(*)
from requests 
group by grouping sets ((os, device, city),(os, device),(os, city),(device,city),(os),(device),(city),());
递归
with recursive tmp as (
    select id,name from user where id=1
    union all
    select test.id,test.name from test join tmp on test.id = tmp.id
) select * from tmp;
注意点
#1.修改表名,视图的表名也会跟着修改,重新备份表数据要特别注意
#2. col !='yyds' and col is null 需要判断null值(高斯数据库)
开窗
first_value() --第1个值
last_value() --最后1个值
lead(col,n,default) --往下n行
lag(col,n,default) --往上n行
row_number() --行序号
dense_rank() --并列,不占位
rank()  --并列,占位

#<窗口函数> over (partition by <用于分组的列名> order by <用于排序的列名> rows/range窗口子句)
rows/range between unbounded preceding and current row
preceding:往前
following:往后
current row:当前行
unbounded:无界限(起点或终点)
unbounded preceding:表示从前面的起点
unbounded following:表示到后面的终点
特殊函数
regexp_split_to_table(col,';')
decode(gender,1,'男',2,'女','未知')
nvl(col1,col2) 

相关推荐

  1. PgSQL高级

    2023-12-13 08:04:01       39 阅读
  2. Pgsql常用命令

    2023-12-13 08:04:01       32 阅读
  3. pgsql存储过程

    2023-12-13 08:04:01       33 阅读
  4. pgsql问题记录

    2023-12-13 08:04:01       55 阅读
  5. mysql2pgsql

    2023-12-13 08:04:01       37 阅读
  6. Oracle-PLSQL

    2023-12-13 08:04:01       38 阅读
  7. PGSQL】date_trunc 函数

    2023-12-13 08:04:01       32 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-13 08:04:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-13 08:04:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-13 08:04:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-13 08:04:01       20 阅读

热门阅读

  1. 环境部署centos

    2023-12-13 08:04:01       32 阅读
  2. 22222222222222222

    2023-12-13 08:04:01       30 阅读
  3. 华纳云:Ubuntu怎么安装并使用Docker

    2023-12-13 08:04:01       37 阅读
  4. 研发管理的挑战、本原与方案

    2023-12-13 08:04:01       48 阅读
  5. RISC-V 流水线 CPU 设计 Verilog

    2023-12-13 08:04:01       31 阅读
  6. Web5:互联网发展的下一个前沿

    2023-12-13 08:04:01       40 阅读