zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    成都磨子桥技工学校 / 数据结构 Challenge 4
    圆桌问题(网络流24题)
    试题库问题(网络流24题)
    [AHOI2005]航线规划
    [AMPPZ2014]The Prices
    方格取数(网络流24题)
    太空飞行计划问题(网络流24题)
    Linux 学习3
    Linux 学习2
    Linux 学习1
  • 原文地址:https://www.cnblogs.com/alianbog/p/5672018.html
Copyright © 2011-2022 走看看