相似Oracle ,PostgreSQL也有強大的類型轉換函數, 下面僅舉兩個類型轉換例子。java
--1 例子
postgres=# select 1/4;
?column?
----------
0
(1 row)sql
在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)post
--4 關於 cast 函數的用法
postgres=# SELECT substr(CAST (1234 AS text), 3,1);
substr
--------
3
(1 row)spa
--5 附: PostgreSQL 類型轉換函數orm
Function | Return Type | Description | Example |
---|---|---|---|
)blog |
text |
convert time stamp to string | to_char(current_timestamp, 'HH12:MI:SS') |
to_char ( interval, text ) |
text |
convert interval to string | to_char(interval '15h 2m 12s', 'HH24:MI:SS') |
to_char ( int, text ) |
text |
convert integer to string | to_char(125, '999') |
precision |
text |
convert real/double precision to string | to_char(125.8::real, '999D9') |
to_char ( numeric, text ) |
text |
convert numeric to string | to_char(-125.8, '999D99S') |
to_date (text, text ) |
date |
convert string to date | to_date('05 Dec 2000', 'DD Mon YYYY') |
to_number ( text, text ) |
numeric |
convert string to numeric | to_number('12,454.8-', '99G999D9S') |
to_timestamp ( text, text ) |
timestamp with time zone |
convert string to time stamp | to_timestamp('05 Dec 2000', 'DD Mon YYYY') |
to_timestamp ( double precision ) |
timestamp with time zone |
convert Unix epoch to time stamp | to_timestamp(1284352323) |
1 | varchar | java.lang.String | 12 | |
2 | bpchar | java.lang.String | 1 | |
3 | cidr | java.lang.Object | 1,111 | |
4 | inet | java.lang.Object | 1,111 | |
5 | macaddr | java.lang.Object | 1,111 | |
6 | text | java.lang.String | 12 | |
7 | int8 | java.lang.Long | -5 | |
8 | int8 | java.lang.Long | -5 | |
9 | box | java.lang.Object | 1,111 | |
10 | circle | java.lang.Object | 1,111 | |
11 | float8 | java.lang.Double | 8 | |
12 | int4 | java.lang.Integer | 4 | |
13 | interval | java.lang.Object | 1,111 | |
14 | line | java.lang.Object | 1,111 | |
15 | lseg | java.lang.Object | 1,111 | |
16 | money | java.lang.Double | 8 | |
17 | numeric | java.math.BigDecimal | 2 | |
18 | path | java.lang.Object | 1,111 | |
19 | point | java.lang.Object | 1,111 | |
20 | polygon | java.lang.Object | 1,111 | |
21 | float4 | java.lang.Float | 7 | |
22 | int2 | java.lang.Integer | 5 | |
23 | int4 | java.lang.Integer | 4 | |
24 | time | java.sql.Time | 92 | |
25 | timestamp | java.sql.Timestamp | 93 | |
26 | bit | java.lang.Boolean | -7 | |
27 | varbit | java.lang.Object | 1,111 | |
28 | bool | java.lang.Boolean | -7 | |
29 | bytea | [B | -2 |