• I'm not sure if I can be of great help. My problem is that I can't see what you see.

    I gave you a link to an article that explains very clearly how to do what you need (it has a first part that you should read if you don't understand fully of what the article talks about).

    I can give you some code, but I can't test it and I'm not sure if it will work.

    In order to help you more, please read the article linked in my signature to help you post DDL, sample data and expected results based on the sample data.

    DECLARE @SQL1 varchar( 40) = '',

    @SQL2 varchar( 8000) = '',

    @SQL3 varchar( 60) = ''

    ;WITH Numbers(RN) AS(

    SELECT DISTINCT RN

    FROM (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3)TMP_URE(RN) --This line should use your table.

    )

    SELECT @SQL2 = @SQL2 + '

    ,MAX(CASE WHEN N=' + CAST( RN AS varchar(2)) + ' THEN MD ELSE NULL END) AS MD' + CAST( RN AS varchar(2)) + ',

    MAX(CASE WHEN N=' + CAST( RN AS varchar(2)) + ' THEN BN ELSE NULL END) AS BN' + CAST( RN AS varchar(2))

    FROM Numbers

    ORDER BY RN

    SET @SQL1 = 'SELECT MK

    ,HK

    ,CK'

    SET @SQL3 = '

    FROM TMP_URE

    GROUP BY MK, HK, CK

    ORDER BY MK, HK, CK'

    PRINT @SQL1 + @SQL2 + @SQL3

    EXEC( @SQL1 + @SQL2 + @SQL3)

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2