美文网首页
case when 使用

case when 使用

作者: mysimplebook | 来源:发表于2020-09-08 11:34 被阅读0次

如下一个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,来解决,否则就需要使用联接语法了。

相关文章

网友评论

      本文标题:case when 使用

      本文链接:https://www.haomeiwen.com/subject/ncudektx.html