SQL新手,欢迎任何帮助。
任何人都可以就创建以下查询的最佳方法提出建议。
_hs_eb_code1 = 'bf', then set format = _hs_eb_det1
_hs_eb_code# = 'bf', then set format = _hs_eb_det#
Repeat until _hs_eb_code# (1-9),
但是,如果_hs_eb_det1
的字符长度超过100个字符,则前缀为'*'
。另外_hs_eb_code1 ='bf'是一个,而_hs_eb_det1将提供许多结果。
到目前为止,我可以使用案例查询来检查第一部分,然后构建另一个查询。我迷路了。
查询:
SELECT CASE
WHEN LEN(FORMAT) < 100 THEN LEFT(FORMAT,100)
ELSE '*'+FORMAT
END AS FORMAT
FROM (SELECT CASE
WHEN EXISTS (SELECT _HS_EB_CODE1 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE1 = 'BF') THEN _HS_EB_DET1
WHEN EXISTS (SELECT _HS_EB_CODE2 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE2 = 'BF') THEN _HS_EB_DET2
WHEN EXISTS (SELECT _HS_EB_CODE3 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE3 = 'BF') THEN _HS_EB_DET3
WHEN EXISTS (SELECT _HS_EB_CODE4 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE4 = 'BF') THEN _HS_EB_DET4
WHEN EXISTS (SELECT _HS_EB_CODE5 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE5 = 'BF') THEN _HS_EB_DET5
WHEN EXISTS (SELECT _HS_EB_CODE6 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE6 = 'BF') THEN _HS_EB_DET6
WHEN EXISTS (SELECT _HS_EB_CODE7 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE7 = 'BF') THEN _HS_EB_DET7
WHEN EXISTS (SELECT _HS_EB_CODE8 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE8 = 'BF') THEN _HS_EB_DET8
WHEN EXISTS (SELECT _HS_EB_CODE9 FROM DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE9 = 'BF') THEN _HS_EB_DET9
END ) AS FORMAT
FROM DBO.SRC_TBM_BILLGRP
但我遇到的问题是查询有一对多,因此无法正常工作。 什么时候出现(从DBO.SRC_HBL_CLNT_CAT WHERE _HS_EB_CODE1 ='BF'中选择_HS_EB_CODE1)那么_HS_EB_DET1
答案 0 :(得分:2)
select case when len(format) > 100 then left(format, 100) + '*' else format end as format from
(select case 'bf' when _hs_eb_code1 then _hs_eb_det1
when _hs_eb_code2 then _hs_eb_det2
when _hs_eb_code3 then _hs_eb_det3
when _hs_eb_code4 then _hs_eb_det4
when _hs_eb_code5 then _hs_eb_det5
when _hs_eb_code6 then _hs_eb_det6
when _hs_eb_code7 then _hs_eb_det7
when _hs_eb_code8 then _hs_eb_det8
when _hs_eb_code9 then _hs_eb_det9
end) as format
from <yourtable>) a