postgresql----条件表达式

postgresql支持CASE,COALESCE,NULLIF,GREATEST,LEAST条件表达式,使用它们有时候可以简化许多功能实现。

测试表

test=# create table tbl_test(id int,name varchar(32),sex varchar(1));
CREATE TABLE
test=# insert into tbl_test values(1,'张三','m'),(2,'李四','m'),(3,'王五','f');
INSERT 0 3

 

CASE

CASE类似其他语言中的if/else等,当符合不同条件时则进行不同的运算。

示例1.查询tbl_test表,如果sex等于'm'则显示'男',,如果是'f'则显示'女'

test=# select name,case when sex = 'm' then '' else '' end as sex from tbl_test;
 name | sex 
------+-----
 张三 | 男
 李四 | 男
 王五 | 女
(3 rows)

 

示例2.查询tbl_test表中男女的人数

方法1.分别查询

test=# select count(*) asfrom tbl_test where sex = 'f';
 女 
----
  1
(1 row)

test=# select count(*) asfrom tbl_test where sex = 'm';
 男 
----
  2
(1 row)

 

方法2.使用case一次查询

test=# select sum(case when sex = 'm' then 1 else 0 end) as 男,sum(case when sex='f' then 1 else 0 end)asfrom tbl_test;
 男 |----+----
  2 |  1
(1 row)

 

coalesce

coalesce(value[,...])

入参个数不限,返回参数中第一个非NULL值。

test=# select coalesce(null,null,1,2,3);
 coalesce 
----------
        1
(1 row)

test=# select coalesce(null,null,'one','two');
 coalesce 
----------
 one
(1 row)

 

NULLIF

nullif(arg1,arg2)

如果两个参数值相等则返回NULL,否则返回arg1.

test=# \pset null 'NULL'
Null display is "NULL".
test=# 
test=# 
test=# select nullif(1,1);
 nullif 
--------
   NULL
(1 row)

test=# select nullif(1,2);
 nullif 
--------
      1
(1 row)

 

GREATEST和LEAST

GREATEST(value [, ...])
LEAST(value [, ...])

入参个数不限,分别返回入参中的最大和最小值

test=# select greatest(1,2,3,4);
 greatest 
----------
        4
(1 row)

test=# select greatest('a','b','c','d');
 greatest 
----------
 d
(1 row)

test=# select least('a','b','c','d');
 least 
-------
 a
(1 row)

test=# select least(1,2,3,4);
 least 
-------
     1
(1 row)

 

posted @ 2016-07-14 22:50  alianblog  阅读(24866)  评论(0编辑  收藏  举报