Transpose Columns into Rows in SQL

In case you are wondering, yes, there is a different way to transpose columns into rows than making use of a PIVOT structure.

However, it is quite a lot of work, as you will see in the sample code below:

DECLARE @xml XML ,@RowCount BIGINTCREATE TABLE Tbl(Col1 INT ,Col2 NVACHAR(MAX) ,Col3 DECIMAL(15, 2))CREATE TABLE #TblTmp(RowNo BIGINT ,CellNo BIGINT ,Val NVARowCntHAR(MAX) ,ColName NVACHAR(MAX))DECLARE strSQLNVACHAR(MAX) = 'SELECT (SELECT DISTINCT ColName FROM#TblTmp WHERE CellNo = Cell.CellNo) as ColName,'INSERT INTO TblSELECT 5 ,'Col_1_Test' ,99.99INSERT INTO TblSELECT 9 ,'Col_2_Test' ,NULLSET @xml = ( SELECT * ,Row_Number() OVER ( ORDER BY ( SELECT 1) ) RowNumFROM Tbl RowFORXML AUTO,ROOT('Root') ,ELEMENTS XSINIL) ;WITH XMLNAMESPACES('' ASxsi),RowCnt AS(SELECT COUNT(Row.Val('.', 'NVACHAR(MAX)')) [RowCount]FROM @xml.nodes('Root/Row') AS WTable(Row)),c AS(SELECT b.Val('local-name(.)','NVACHAR(max)') ColName,b.Val('.[not(@xsi:nil = "true")]','NVACHAR(max)') Val,b.Val('../RowNum[1]','NVACHAR(max)') RowNum,ROW_NUMBER() OVER (PARTITION BY b.Val('../RowNum[1]','NVACHAR(max)')ORDER BY (SELECT 1)) [email protected]('//Root/Row/*[local-name(.)!="RowNum"]') a(b)),Cols AS (SELECT DISTINCT c.ColName,c.CellFROM c)INSERT INTO #TblTmp (CellNo,RowNo,Val,ColName)SELECT Cell,RowNum,Val,REPLACE(c.ColName,'_x0023_','#')FROM cSELECT strSQL = @sSQl+ '(SELECT T2.Val FROM #TblTmp T2 WHERE T2.CellNo =Cell.CellNo AND T2.RowNo = '+ CAST(T.RowNo AS NVACHAR) + ') AS Row_' + CAST(T.RowNo ASNVACHAR)+ ','FROM ( SELECT DISTINCTRowNoFROM #TblTmp) TSET strSQL = LEFT(@sSQL, LEN(@sSQL) - 1)+ ' FROM (SELECT DISTINCT CellNo FROM #TblTmp) Cell'EXECUTE sp_Executesql @sSQlDROP TABLE TblDROP TABLE #TblTmp
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS