SQL中Case的使用方法以及nvl的使用案例
1.SQL中Case的使用方法
Case具有两种格式。简单Case函数和Case搜索函数。
--简单Case函数
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
--Case搜索函数
CASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END
这两种方式,可以实现相同的功能。简单Case函数的写法相对比较简洁,但是和Case搜索函数相比,功能方面会有些限制,比如写判断式。
还有一个需要注意的问题,Case函数只返回第一个符合条件的值,剩下的Case部分将会被自动忽略。
2.nvl(字段,默认值) 用于判断字段是否为空,用于处理空值的。若为空,返回指代的值,否则返回本身字段的值。
3.案例:
需求:在商户表(URMTMINF)
中根据信用级别CRED_LVL查询商户信息(含有业务代码字段MERC_TRD_CLS)。
将根据查询到的业务代码,到对应URMTTRADECONF表查询业务描述(MERC_TRD_DESC)。
其中先根据旧关联f.MERC_TRD_CLS_OLD=B.MERC_TRD_CLS,如果业务描述为空,在根据新字段关联WHERE MERC_TRD_CLS = B.MERC_TRD_CLS,如果仍为空,就赋予常量‘其他’
中根据信用级别CRED_LVL查询商户信息(含有业务代码字段MERC_TRD_CLS)。
将根据查询到的业务代码,到对应URMTTRADECONF表查询业务描述(MERC_TRD_DESC)。
其中先根据旧关联f.MERC_TRD_CLS_OLD=B.MERC_TRD_CLS,如果业务描述为空,在根据新字段关联WHERE MERC_TRD_CLS = B.MERC_TRD_CLS,如果仍为空,就赋予常量‘其他’
sql:
SELECT B.MERC_ID,
B.MERC_CNM,
B.MERC_ABBR,
(CASE
WHEN B.MERC_PROV IS NOT NULL THEN
(SELECT FLD_EXP
FROM PUBTHLP
WHERE FLD_NM = 'PROV_CD'
AND FLD_VAL = B.MERC_PROV)
ELSE
B.MERC_PROV
END) AS MERC_PROV_DESC,
(CASE
WHEN B.MERC_TYP IS NOT NULL THEN
(SELECT FLD_EXP
FROM PUBTHLP
WHERE FLD_NM = 'MERC_TYP'
AND FLD_VAL = B.MERC_TYP)
ELSE
B.MERC_TYP
END) AS MERC_TYP_DESC,
(CASE
WHEN B.CRED_LVL IS NOT NULL THEN
(SELECT FLD_EXP
FROM PUBTHLP
WHERE FLD_NM = 'MERC_LVL'
AND FLD_VAL = B.CRED_LVL)
ELSE
B.CRED_LVL
END) AS CRED_LVL_DESC,
(CASE
WHEN B.MERC_TRD_CLS IS NOT NULL THEN
NVL(NVL((CASE
WHEN (SELECT COUNT(MERC_TRD_DESC) FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS_OLD = B.MERC_TRD_CLS)>1 THEN
(SELECT DISTINCT MERC_TRD_DESC1
FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS_OLD = B.MERC_TRD_CLS)
ELSE
(SELECT MERC_TRD_DESC
FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS_OLD = B.MERC_TRD_CLS)
END), (SELECT MERC_TRD_DESC
FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS = B.MERC_TRD_CLS)), '其他') ELSE '其他' END) AS MERC_TRD_DESC
FROM URMTMINF B
WHERE CRED_LVL = ?
B.MERC_CNM,
B.MERC_ABBR,
(CASE
WHEN B.MERC_PROV IS NOT NULL THEN
(SELECT FLD_EXP
FROM PUBTHLP
WHERE FLD_NM = 'PROV_CD'
AND FLD_VAL = B.MERC_PROV)
ELSE
B.MERC_PROV
END) AS MERC_PROV_DESC,
(CASE
WHEN B.MERC_TYP IS NOT NULL THEN
(SELECT FLD_EXP
FROM PUBTHLP
WHERE FLD_NM = 'MERC_TYP'
AND FLD_VAL = B.MERC_TYP)
ELSE
B.MERC_TYP
END) AS MERC_TYP_DESC,
(CASE
WHEN B.CRED_LVL IS NOT NULL THEN
(SELECT FLD_EXP
FROM PUBTHLP
WHERE FLD_NM = 'MERC_LVL'
AND FLD_VAL = B.CRED_LVL)
ELSE
B.CRED_LVL
END) AS CRED_LVL_DESC,
(CASE
WHEN B.MERC_TRD_CLS IS NOT NULL THEN
NVL(NVL((CASE
WHEN (SELECT COUNT(MERC_TRD_DESC) FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS_OLD = B.MERC_TRD_CLS)>1 THEN
(SELECT DISTINCT MERC_TRD_DESC1
FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS_OLD = B.MERC_TRD_CLS)
ELSE
(SELECT MERC_TRD_DESC
FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS_OLD = B.MERC_TRD_CLS)
END), (SELECT MERC_TRD_DESC
FROM payadm.URMTTRADECONF
WHERE MERC_TRD_CLS = B.MERC_TRD_CLS)), '其他') ELSE '其他' END) AS MERC_TRD_DESC
FROM URMTMINF B
WHERE CRED_LVL = ?
博客:https://kunnan.blog.csdn.net