将列数据转换为行

时间:2016-03-18 17:12:19

标签: tsql

必须有一种更简单的方法来做到这一点,对吧?我有100行数值,我希望第一行在新表中,第1行第A列,第二行在新表中,第1行第B列,...第100行在新表中table,row 100 column J.为了好玩,我还在一个基于该数值的单个字母写入新表,而不是数字。所以这是我的代码:

UPDATE #data
SET Block = CASE OStatus WHEN 1 THEN 'C' WHEN 2 THEN 'B'
    WHEN 3 THEN 'D' WHEN 4 THEN 'S' WHEN 5 THEN 'P' ELSE '' END

DECLARE  @Ax NVARCHAR(1)
    ,@Bx NVARCHAR(1)
    ,@Cx NVARCHAR(1)
    ,@Dx NVARCHAR(1)
    ,@Ex NVARCHAR(1)
    ,@Fx NVARCHAR(1)
    ,@Gx NVARCHAR(1)
    ,@Hx NVARCHAR(1)
    ,@Ix NVARCHAR(1)
    ,@Jx NVARCHAR(1)

SET @Count1 = 0
WHILE @Count1 < 10 BEGIN
SET @Count1 += 1

SELECT @Ax = Block FROM #data WHERE ID = @Count1 +  0
SELECT @Bx = Block FROM #data WHERE ID = @Count1 + 10
SELECT @Cx = Block FROM #data WHERE ID = @Count1 + 20
SELECT @Dx = Block FROM #data WHERE ID = @Count1 + 30
SELECT @Ex = Block FROM #data WHERE ID = @Count1 + 40
SELECT @Fx = Block FROM #data WHERE ID = @Count1 + 50
SELECT @Gx = Block FROM #data WHERE ID = @Count1 + 60
SELECT @Hx = Block FROM #data WHERE ID = @Count1 + 70
SELECT @Ix = Block FROM #data WHERE ID = @Count1 + 80
SELECT @Jx = Block FROM #data WHERE ID = @Count1 + 90

INSERT INTO _dbh_grid
 SELECT
 @Ax,@Bx,@Cx,@Dx,@Ex,@Fx,@Gx,@Hx,@Ix,@Jx

END

1 个答案:

答案 0 :(得分:2)

我使用PIVOT功能(和一点点数学运算)来使它工作;你可能会让它充满活力。

/*build a sample data set*/

SELECT TOP 100
        column_id AS OSStatus
      , ID = IDENTITY( INT, 1,1)
INTO    #data
FROM    sys.columns
WHERE   column_id < 6;

SELECT *
FROM #data d;


/*break the data set into groups of 10, and identify the ordinal position within each group
column_postition returns group
row_position returns ordinal within group
*/
WITH    c AS ( SELECT   OSStatus
                      , column_position = ( ROW_NUMBER() OVER ( ORDER BY ID )
                                            - 1 ) / 10
                      , row_position = ( ROW_NUMBER() OVER ( ORDER BY ID ) - 1 )
                        % 10
               FROM     #data
             )
    SELECT  [A], [B], [C], [D], [E], [F], [G], [H], [I], [J]

    FROM    ( SELECT    c.OSStatus
                      , column_name = CHAR(65 + c.column_position) --convert to a-J
                      , c.row_position
              FROM      c
            ) p
    PIVOT
        (MIN(OsStatus)
         FOR column_name
         IN ([A], [B], [C], [D], [E], [F], [G], [H], [I], [J])
         ) pvt


DROP TABLE #data;