In the ETL project often encounter such a situation:
A column in the target table originates from a different source data table A,b,c. If no valid data in A is taken from B, if none in B is taken from C, then set to null if none is in C.
In situations like this, sometimes the first thought is the case and then else end, which can solve the problem, but it's still more complicated and error-prone, especially when someone looks at the SQL you're writing.
So is there a better way?
That's the COALESCE function.
The COALESCE function can replace case statements and is much more convenient than case, coalesce format: Coalesce (expression_1, expression_2, ..., expression_n).
The first non-null expression is the return value of the function, and if all of the expressions are NULL, a null value will eventually be returned.
Here is a practical example of the project:
Problem Description: The target table is a column of data from Hr.mgr_entitycode, PS. BRAND_CD, ps.org, if Hr.mgr_entitycode is not empty then from PS. BRAND_CD, PS. The org takes a value and returns null if both are empty.
SQL is as follows:
SELECTCi. RESOURCE_ID,COALESCE(HR. Mgr_entitycode, PS. BRAND_CD, ps.org) cal_brand_cd,ci. BRAND_CD fromtestenv. Cr__items asDR. Left OUTER JOINTestenv. Pr_items asPri onCi. Po_key=PRI. Po_key Left OUTER JOINTestenv. Purchase_summary asPs onPri. Po_key=Ps. Po_key andPri. Po_item_num=PS. Po_m_num Left OUTER JOINTestenv.hr_cld_cont asHR onCi. resource_id=HR. resource_id withUR;
Application of coalesce function in DB2