美文网首页
PostgreSQL笔记

PostgreSQL笔记

作者: one_little_boy | 来源:发表于2019-06-28 17:12 被阅读0次

1.时间

四种方式查询当前时间now() , current_date, current_time, current_timestamp, 其中now() 等同于 current_timestamp

1.当前时间向前推一天
SELECT now() + interval '1 day'
SELECT current_timestamp - interval '1 day'
例:求出最近三天的数据
select * from 表名 where date between (SELECT current_timestamp - interval '3 day') and current_timestamp
2.当前时间向前推进一个月
SELECT current_timestamp - interval '1 month'
3.当前时间向前推进一年
SELECT current_timestamp - interval '1 year'
4.当前时间向前推一小时:
SELECT current_timestamp - interval '1 hour'
5.当前时间向前推一分钟:
SELECT current_timestamp - interval '1 min'
6.当前时间向前推60秒:
SELECT current_timestamp - interval '60 second'

2.字符串

1.字符串连接(或者与数字连接)
select 'a' || 12 || 'b' ; 返回:a12b
2.查询字符串中的字符个数
select char_length('a123') ; 返回:4
3.截取字符串
select substring('abcdefg' from 2 for 3) ; 返回:bcd
select position('a' in 'abc'); 返回:1
lower(), upper()等...

3.聚合函数

1.返回JSON数组
select json_agg(department_name) from prescription;
返回:["心内科", "肾内科", "心内科", "心内科", "皮肤科门诊", "心内科", "心内科", "皮肤科门诊", "心内科", "心内科", "心内科", "心内科", "心内科", "心内科", "心内科", "皮肤科门诊", "肾内科", "心内科", "心内科", "心内科", "心内科", "皮肤科门诊", "肾内科1", "内分泌科", "内分泌科", "心内科", "心内科", "心内科", "心内科", "肾内科1"]
2.返回JSON数组并去重
select json_agg(distinct(department_name)) from prescription;
返回:["内分泌科", "心内科", "皮肤科", "皮肤科门诊", "肾内科", "肾内科1"]
3.行转列 string_agg
测试表

eno | ename | job | mgr | hiredate | sal | comm | deptno
------+--------+----------+------+---------------------+------+------+--------
7499 | ALLEN | SALESMAN | 7698 | 1991-02-20 00:00:00 | 1600 | 300 | 30
7566 | JONES | MANAGER | 7839 | 1991-04-02 00:00:00 | 2975 | | 20
7654 | MARTIN | SALESMAN | 7698 | 1991-09-28 00:00:00 | 1250 | 1400 | 30
7498 | JASON | ENGINEER | 7724 | 1990-02-20 00:00:00 | 1600 | 300 | 10

将部门为30的员工的姓名合并起来
Select deptno,string_agg(ename,',') from table group by deptno;
deptno | string_agg
----------+--------------
30 | ALLEN,MARTIN
10 | JASON
20 | JONES
例:SELECT department_id, string_agg(doctor_code,',') FROM doctor group by department_id

相关文章

  • PostgreSQL笔记

    修改字段名 修改字段 新增字段 查找字符串 tab的使用 情景:批量新增 灾难性SQL【update关于多个表】

  • PostgreSQL笔记

    1.时间 四种方式查询当前时间now() , current_date, current_time, curr...

  • postgresql学习笔记--基础篇 -psql工具

    【技术学习】postgresql学习笔记--基础篇 -psql工具 --创建用户CREATEROLE pguser...

  • PostGIS 笔记一:简单入门

    PostGIS 笔记一:简单入门 Postgis是基于PostgreSQL的空间扩展。所以你懂得PostgreSQ...

  • postgresql debug

    postgresql architecture postgresql build postgresql debug...

  • PostgreSQL安装笔记

    1. macOS: 1.1. 安装 1.1.1. 使用命令安装: 安装:brew install postgres...

  • Postgresql注入笔记

    Postgresql注入笔记 一、前期准备 1. 测试环境 2. 测试数据结构和内容 3. 调用postgresq...

  • Postgresql学习笔记

    概述 postgresql是一个开源的关系型数据库,可以作为mysql的替代品。本篇意在让读者快速的了解postg...

  • PostgreSQL安装笔记

    安装PG 配置修改认证方式为md5 添加 允许远程连接的ip 修改默认用户密码 参考:PostgreSQL本地登录...

  • postgreSQL - 学习笔记

    增删改查 字段 索引 视图 事务 增删改查 字段 索引 视图 事务

网友评论

      本文标题:PostgreSQL笔记

      本文链接:https://www.haomeiwen.com/subject/grvscctx.html