Please help me get the data from the input table in the form of an output table using SQL. There are more than 60 status codes in data so a query which is reproducible is desire. A query that automatically transforms the 60 status codes to columns.
Currently, I am using the below query but with this query, the problem is if a new status code is created it needs to be updated Can you please give me a solution to automate this query if a new status code is introduced.
WITH PivotData AS
(
SELECT
[acctrefno]
,LSC.status_code
,1 AS Qty
FROM [NLS].[dbo].[loanacct_statuses] LS
INNER JOIN loan_status_codes LSC ON LSC.status_code_no = LS.status_code_no
)
SELECT acctrefno, [PIF], [CUR], [DUE], [WCC]
FROM PivotData
PIVOT( SUM(Qty) FOR Status_code IN([PIF], [CUR], [DUE], [WCC])) AS P