Application of coalesce function in DB2

Source: Internet
Author: User
Tags db2

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.