程序里错误码和字典对应不上,要做二次加工,回顾了一下case when的使用,直接在SQL里处理一下
case when的两种写法
简单判断:
要判断值的列写在case后面,when后面写值,相等的情况执行then后的语句,可以写多个when判断语句,都不满足返回else后的值,要以end结尾,end后面可以给该列指定列名。
CASE [col_name] WHEN [value1] THEN [result1] WHEN [value1] THEN [result2] .... ELSE [default] END [new_col_name]
表达式判断:
case开头,when后面写表达式,表达式为真则执行then后的语句,可以写多个when判断表达式,都不满足的情况下返回else后的值,以end结尾,end后可以为该列指定列名。
CASE WHEN [expr] THEN [result1] WHEN [expr] THEN [result2] .... ELSE [default] END [new_col_name]
case when可以写在select后,可以写在where语句中,也可以联合表的时候写在联合的on语句中
下面是对错误码进行二次加工的例子
select a.khh,a.warning_type ,b.error_type,b.error_name,count(*) from ( select khh,warning_type, error_code from t_client_response_info where log_date>=‘10838‘ and log_date<‘10853‘ ) a LEFT JOIN t_error_code b on a.warning_type = b.alarm_type and (case when SUBSTR(a.error_code, 1, 4) in (‘0002‘,‘0005‘,‘0006‘,‘0007‘,‘0008‘,‘0009‘) then CONCAT(SUBSTR(a.error_code, 1, 4),‘0000‘) when SUBSTR(a.error_code, 1, 6) in (‘000C01‘,‘000C02‘) then CONCAT(SUBSTR(a.error_code, 1, 6),‘00‘) when SUBSTR(a.error_code, 1, 3) =‘066‘ and SUBSTR(a.error_code, 1, 6) != ‘06600‘ then CONCAT(SUBSTR(a.error_code, 1, 5),‘000‘) when SUBSTR(a.error_code, 1, 2) =‘06‘ and SUBSTR(a.error_code, 1, 3) != ‘066‘ then CONCAT(SUBSTR(a.error_code, 1, 2),‘00‘,SUBSTR(a.error_code, 5, 4)) else a.error_code end) = b.error_code group by a.khh,a.warning_type,b.error_type,b.error_name;
原文地址:https://www.cnblogs.com/zhaoshizi/p/11552286.html
时间: 2024-10-14 19:04:17