I split some values (REPAY_AMOUNT and REPAY_REF) which are delimited special character and cross applied them as follows:
SELECT
ARRANGEMENT_ID,
REPAY_AMOUNT,
REPAY_REF,
CAST(RIGHT(RR.Value,8) AS DATE) 'Split Date',
RA.Value 'Split Amt'
FROM AA_BILL_DETAILS_Property
CROSS APPLY OPENJSON(CONCAT('["', REPLACE(REPAY_REF, N'', '","'), '"]')) RR
CROSS APPLY OPENJSON(CONCAT('["', REPLACE(REPAY_AMOUNT, N'', '","'), '"]')) RA
WHERE RR.[key] = RA.[key]
ORDER BY [Split Date] DESC
Results are:
| ARRANGEMENT_ID | REPAY_AMOUNT | REPAY_REF | Split Date | Split Amt |
|---|---|---|---|---|
| AA21084T517V | 3678.412050.25 | AAACT223212XPWZDCY-20221117AAACT222933SXX4KLB-20221020 | 2022-11-17 | 3678.41 |
| AA21084T517V | 3678.412050.25 | AAACT223212XPWZDCY-20221117AAACT222933SXX4KLB-20221020 | 2022-10-20 | 2050.25 |
| AA21084T517V | 1931.41931.4 | AAACT22059QK5XTXSD-SUSPEND-20220228AAACT22059QK5XTXSD-20220228 | 2022-02-28 | 1931.4 |
| AA21084T517V | 1931.41931.4 | AAACT22059QK5XTXSD-SUSPEND-20220228AAACT22059QK5XTXSD-20220228 | 2022-02-28 | 1931.4 |
| AA21084T517V | NULL | NULL | 1900-01-01 | |
| AA21084T517V | NULL | NULL | 1900-01-01 |
Problem:
Now I want to split and cross apply another column (PAY_PROPERTY) like:
SELECT
ARRANGEMENT_ID,
REPAY_AMOUNT,
REPAY_REF,
CAST(RIGHT(RR.Value,8) AS DATE) 'Split Date',
RA.Value 'Split Amt',
PAY_PROPERTY,
PP.Value 'PP'
FROM AA_BILL_DETAILS_Property
CROSS APPLY OPENJSON(CONCAT('["', REPLACE(REPAY_REF, N'', '","'), '"]')) RR
CROSS APPLY OPENJSON(CONCAT('["', REPLACE(REPAY_AMOUNT, N'', '","'), '"]')) RA
CROSS APPLY OPENJSON(CONCAT('["', REPLACE(PAY_PROPERTY, N'', '","'), '"]')) PP
WHERE RR.[key] = RA.[key] AND RR.[key] = PP.[key]
ORDER BY [Split Date] DESC
But doing so, I lose one row (i-e, one of the rows having Split Amt = 1931.4) resulting in:
| ARRANGEMENT_ID | REPAY_AMOUNT | REPAY_REF | Split Date | Split Amt | Pay_Property | PP |
|---|---|---|---|---|---|---|
| AA21084T517V | 3678.412050.25 | AAACT223212XPWZDCY-20221117AAACT222933SXX4KLB-20221020 | 2022-11-17 | 3678.41 | ACCOUNTPRINCIPALINT | ACCOUNT |
| AA21084T517V | 3678.412050.25 | AAACT223212XPWZDCY-20221117AAACT222933SXX4KLB-20221020 | 2022-10-20 | 2050.25 | ACCOUNTPRINCIPALINT | PRINCIPALINT |
| AA21084T517V | 1931.41931.4 | AAACT22059QK5XTXSD-SUSPEND-20220228AAACT22059QK5XTXSD-20220228 | 2022-02-28 | 1931.4 | NULL | |
| AA21084T517V | NULL | NULL | 1900-01-01 | NULL | ||
| AA21084T517V | NULL | NULL | 1900-01-01 | NULL |
Can someone help please?
Your problem is that you have an unequal number of split values in each column, so the join condition is failing. You cannot use an
ONclause withAPPLY, so instead you can useOUTER APPLY, which works similarly to aLEFT JOIN, and move theWHEREcondition into theAPPLY.If the other columns also have a variable number of splits then you need a full join:
Note the
ISNULLin the second join condition.db<>fiddle