当前位置: 代码网 > it编程>数据库>MsSqlserver > PostgreSQL的case when语句使用

PostgreSQL的case when语句使用

2024年08月02日 MsSqlserver 我要评论
使用时case when then 的数据类型要相同,否则会报错。下面是自己实际用到的情况,供自己学习记录。上面是在网上搜到的介绍。
case when语句第一种方式:

case 
    when 表达式1 then 结果1
    when 表达式2 then 结果2
    else 结果n
end
举例1:
select sum(
        case
            when rental_rate=0.99 then 1
            else 0
        end
    ) as "aa",
    
    sum(
     case
        when rental_rate=2.99 then 1
        else 0
     end
    ) as "bb",
    
    sum(
        case
            when rental_rate=4.99 then 1
            else 0
        end
    ) as "cc"
    
    from film;
结果:
aa     bb     cc
341    323    336


【注】:as后接的别名需要带双引号,否则报语法错误


case when语句第二种方式:

case 表达式
    when 匹配1 then 结果1
    when 匹配2 then 结果2
    else 结果n
end
举例2:
    select sum(
        case rental_rate
            when 0.99 then 1
            else 0
        end
    ) as "aa",
    
    sum(
        case rental_rate
            when 2.99 then 1
            else 0
        end
    ) as "bb",
    
    sum(
        case rental_rate
            when 4.99 then 1
            else 0
        end
    ) as "cc"
    from film;
结果:
aa     bb     cc
341    323    336

上面是在网上搜到的介绍

下面是自己实际用到的情况,供自己学习记录。

select  c.unit,
		case when d.money ::decimal = 0.00
		then '0%'
		   else concat(round(c.number ::decimal/d.money ::decimal*100,2),'%')  end as rate  
from (
select p.unit,sum(p.number::decimal) as number from table p 
where  p.code in (select  code from code_table ) 
group by  p.unit
) c
left join (
select  unit,sum(money::decimal) as money from code_table 
group by unit
) d
on  c.unit = d.unit 

使用时case when then 的数据类型要相同,否则会报错

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com