CREATE table #yourtable ([SCP_SEQ_NBR] int, [FCST_YR_PRD]...

0

Please login or register to vote for this query.

(click on this box to dismiss)

Quantitative Finance

Q&A for finance professionals and academics

CREATE table #yourtable
    ([SCP_SEQ_NBR] int, [FCST_YR_PRD] varchar(6), [FCST_RSLT_QTY] varchar(13))
;
    
INSERT INTO #yourtable
    ([SCP_SEQ_NBR], [FCST_YR_PRD], [FCST_RSLT_QTY])
VALUES
    (101, '201505', '1'),
    (101, '201506', '2'),
    (101, '201607', '3'),
    (101, '201508', '4'),
    (101, '201509', '5')
;


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(FCST_RSLT_QTY) 
                    from #yourtable
                    group by FCST_RSLT_QTY, SCP_SEQ_NBR
                    order by SCP_SEQ_NBR
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select FCST_RSLT_QTY, FCST_YR_PRD
                from #yourtable
            ) x
            pivot 
            (
                max(FCST_RSLT_QTY)
                for FCST_YR_PRD in (' + @cols + N')
            ) p '

exec sp_executesql @query;

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results