PostgreSQL 常用函数

类似Oracle ,PostgreSQL也有强大的类型转换函数, 下面仅举两个类型转换例子。

      
--1 例子
postgres=# select 1/4;
 ?column? 
----------
        0
(1 row)

        在PG里如果想做除法并想保留小数,用上面的方法却行不通,因为"/" 运算结果为取整,并
且会截掉小数部分。
 

--2 类型转换
postgres=# select round(1::numeric/4::numeric,2);
 round 
-------
  0.25
(1 row)

  备注:类型转换后,就能保留小数部分了。


--3 也可以通过 cast 函数进行转换
postgres=# select round( cast ( 1 as numeric )/ cast( 4 as numeric),2);
 round 
-------
  0.25
(1 row)


--4 关于 cast 函数的用法 substr 索引默认为1 下面是从 第3位开始,截取1位
postgres=# SELECT substr(CAST (1234 AS text), 3,1);   
 substr 
--------
 3
(1 row)

   实例:查询某一天数据

select * from pro.book where cast(create_time as date)='2019/07/30';

 

|| 字符串拼接
语法
string || string
示例
'Post' || 'greSQL' -- 返回PostgreSQL

length() 字符串的长度
语法
length(string)
示例
length('Odoo') -- 返回4

LIKE 模式匹配
语法
string LIKE pattern
示例
’abc’ LIKE ’abc’ -- 返回true
’abc’ LIKE ’a%-- 返回true

to_char() 把时间戳转换成字符串
语法
to_char(timestamp, text)
示例
to_char(create_date, 'YYYY/MM/DD')
to_char(create_date, ’HH12:MI:SS’)

to_date() 把字符串转换成日期
语法
to_date(text, text)
示例
to_date(’05 Jan 2015’,’DD Mon YYYY’)

to_timestamp() 把字符串转换成时间戳
语法
to_timestamp(text, text)
示例
to_timestamp(’05 Jan 2015’, ’DD Mon YYYY’)

CASE 条件表达式, 类似于其他编程语言中的if/else
语法1
CASE WHEN condition THEN result [WHEN ...] [ELSE result] END
示例1
CASE WHEN gender='male' THEN '程序猿' ELSE '程序媛' END
语法2(简化形式)
CASE expression WHEN value THEN result [WHEN ...] [ELSE result] END
示例2
CASE gender WHEN 'male' THEN '程序猿' ELSE '程序媛' END

COALESCE() 返回第一个非NULL的参数,所有参数均为NULL时则返回NULL
语法
COALESCE(value [, ...])
示例
COALESCE(actual_qty,0) as actual_qty

NULLIF() 如果value1与value2相等则返回NULL, 否则返回value1
语法
NULLIF(value1, value2)
示例
NULLIF(value, ’(none)’)

 

posted @ 2019-06-17 20:46  低调码农哥!  阅读(8938)  评论(0编辑  收藏  举报