postgresql case when then else end的用法

case when用法

基本语法:
select case A when B then C else D end E from table
A可以为表中的字段名或者是子查询,总之A是一个表达式
B是表达式的结果,如果A的查询结果等于B,则结果是C,否则是D
E是结果的查询别名,自己定义

多个条件判断
从表中取zpid,zhid(别名 zt)

if(zhid=='CS1'){
zt='1'
} else if(zhid=='zhid01'){
zt='2'
}else{
zt='3'
}

其中else的部分可以省略

包含子查询的例子

SELECT a.xxmc, a.xxbh,
case (select sjtzzbh from la.tzzxx where tzzbh=a.tzzbh) 
when '01' then 1 else 0 end sfssgx
from table a

case when的变形用法,单个表达式含有多个判定条件

可以将判定表达式放到when之后,需要该表达式是一个boolean类型的表达式

	select case   when zhid='cc'  then 1 else 0 end as sfpj 
	from lapos.jygw_pjdf ;

case when 后面也可以接多个判定条件,用and或者or 表示条件成立的“与”或者“或“

	select case   when zhid='cc' and tdid='td01' 
	then 1 else 0 end as sfpj 
	from lapos.jygw_pjdf ;
发布了31 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/cchulu/article/details/103529542