case when 使用

如下一个sql拼接片段

case_parent_platform =" case when from_platform in (2, 3, 7) then '1' " \

"when from_platform in (21, 23, 24, 25, 26, 27, 28) then '2' " \

"when from_platform in (12, 20) then '3' " \

"when from_platform in (0) then '4' " \

"else '5' end as parent_platform, "

  见过,不是太熟悉,很少使用,这里总结一下case when 的使用方法

1、满足条件的列,对值进行替换

如原表table

假如我想将verify_code这一列满足条件的值进行替换,如
select case when verify_code='808096' then 'new' else 'old' end as vt from table

查询结果如下

2、替代where条件,如

select

 ck_out_profit, ck_a_profit

from (

SELECT   supplier_name,

round(sum(case when sale_type in (1,2)  then out_profit else null end),4) as ck_out_profit,

round(sum(case when sale_type in (1,2,3) then gross_profit else null end),4)  as ck_a_profit

from bi_mdata.dm_order_send_detail

where date_str>='2020-11-22' and date_str<='2020-11-22' and supplier_name !='' 

group by  supplier_name) a

如上,不同的字段使用的条件不同,我们可以使用case when,来解决,否则就需要使用联接语法了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容