TSQL Pivot without aggregate function

后端 未结 9 1761
青春惊慌失措
青春惊慌失措 2020-11-22 09:10

I have a table like this...

CustomerID   DBColumnName   Data
--------------------------------------
1            FirstName      Joe
1            MiddleName           


        
9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 09:46

    Ok, sorry for the poor question. gbn got me on the right track. This is what I was looking for in an answer.

    SELECT [FirstName], [MiddleName], [LastName], [Date] 
    FROM #temp 
    PIVOT
    (   MIN([Data]) 
        FOR [DBColumnName] IN ([FirstName], [MiddleName], [LastName], [Date]) 
    )AS p
    

    Then I had to use a while statement and build the above statement as a varchar and use dynmaic sql.

    Using something like this

    SET @fullsql = @fullsql + 'SELECT ' + REPLACE(REPLACE(@fulltext,'(',''),')','')
    SET @fullsql = @fullsql + 'FROM #temp '
    SET @fullsql = @fullsql + 'PIVOT'
    SET @fullsql = @fullsql + '('
    SET @fullsql = @fullsql + ' MIN([Data])'
    SET @fullsql = @fullsql + ' FOR [DBColumnName] IN '+@fulltext
    SET @fullsql = @fullsql + ')'
    SET @fullsql = @fullsql + 'AS p'
    
    EXEC (@fullsql)
    

    Having a to build @fulltext using a while loop and select the distinct column names out of the table. Thanks for the answers.

提交回复
热议问题