I have data that can be populated between 2 fields. One may be null and the other may be populated. I have this expression that looks at one of the fields, I need to incorporate another case when expression or possibly an if then else to accomplish this.
max(case when key_id = 'program.partner' then split(identifier,':')[6] end) as partner_id
I need to incorporate this with the above expression
max(case when key_id = 'partner' then identifier end)
I was thinking something like this, but it is not working
case when (max(case when key_id = 'program.partner' then split(identifier,':')[6]) is null then (max(case when key_id = 'partner' then identifier)) else '' end as partner_id,
I have data that can be populated between 2 fields. One may be null and the other may be populated. I have this expression that looks at one of the fields, I need to incorporate another case when expression or possibly an if then else to accomplish this.
max(case when key_id = 'program.partner' then split(identifier,':')[6] end) as partner_id
I need to incorporate this with the above expression
max(case when key_id = 'partner' then identifier end)
I was thinking something like this, but it is not working
case when (max(case when key_id = 'program.partner' then split(identifier,':')[6]) is null then (max(case when key_id = 'partner' then identifier)) else '' end as partner_id,
Share
Improve this question
edited Mar 25 at 9:01
Dale K
27.5k15 gold badges58 silver badges83 bronze badges
asked Mar 19 at 18:17
suzysuzy
215 bronze badges
3
- 3 Match your round brackets. You are missing a close bracket for your first open bracket. – Bart McEndree Commented Mar 19 at 18:23
- 1 Please provide both sample input data and expected result. It's unclear what exactly you want to do and therefore, we don't know whether you are on the right track. – Jonas Metzler Commented Mar 19 at 18:28
- 3 What SQL dialect uses split() ? – Bart McEndree Commented Mar 19 at 18:29
1 Answer
Reset to default 1Considering No Input data or expected output is given, In general, I suggest try COALESCE
and CASE
expressions. The COALESCE
function returns the first non-null value in the list of arguments. Here's an example of how you can incorporate both conditions into a single statement:
COALESCE(
max(case when key_id = 'program.partner' then split(identifier, ':')[6] end),
max(case when key_id = 'partner' then identifier end)
) as partner_id
Explanation:
CASE
Expressions: EachCASE
expression checks for a specifickey_id
and extracts the desired value.MAX
Function: TheMAX
function is used to ensure that we get the maximum value from the results of theCASE
expressions.COALESCE
Function: TheCOALESCE
function returns the first non-null value from the list of arguments. If the result of the firstCASE
expression isNULL
, it will return the result of the secondCASE
statement.
This way, if the value for key_id = 'program.partner'
is NULL
, it will fall back to the value for key_id = 'partner'
.