I have 4 Common Table Expressions each contains 2 columns (RowNumber, AccountNumber) but contain variable records in each CTE depending upon the query parameters. Purpose is to keep all non null account numbers at the top for each CTE after joining.
I am joining 4 CTE's using FULL Join on the basis of RowNumber. The problem I am getting is the sequence of AccountNumber is not continuous i.e. it includes some null values in between Accountnumber in some cases. I want to keep all non null values always combined and at the top with nulls. The number of AccountNumber's in each CTE are always different.
SELECT
ISNULL(Cte_FirstYear.AccountNumber,'') as FirstYear,
ISNULL(Cte_SecondYear.AccountNumber,'') as SecondYear,
ISNULL(cte_ThirdYear.AccountNumber,'') as ThirdYear,
ISNULL(cte_FourthYear.AccountNumber,'') as FourthYear
FROM cte_ThirdYear
FULL OUTER JOIN
cte_FirstYear
on
cte_ThirdYear.RowNumber=cte_FirstYear.RowNumber
full outer join Cte_SecondYear
on
cte_ThirdYear.RowNumber=Cte_SecondYear.RowNumber
full outer join cte_FourthYear
on
cte_ThirdYear.RowNumber=cte_FourthYear.RowNumber
Here is how I am getting the output;
FirstYear SecondYear ThirdYear FourthYear
1 2 3 4
5 6 7 1
9 NULL NULL
NULL
9 9
10 NULL
Here is expected output;
FirstYear SecondYear ThirdYear FourthYear
1 2 3 4
5 6 7 1
9 9 9
10