使用pivot SQL查询将行转换为列

时间:2016-07-08 11:17:25

标签: sql-server

我有以下格式的数据:

http://i.stack.imgur.com/SpHnz.png

可能会有一个人告诉我如何将其转移到:

http://i.stack.imgur.com/wulVc.png

我为每个BatchNo和TransactionDate设置了多组这样的行,并希望将一个batchno旋转到一行,依此类推....

更新从评论尝试的SQL无效(参见详情评论):

SELECT 
  [1] UnitId, [2] Time, [4] Date, [5] A, [6] a, [8] b, [9] c, [10] ABT, 
  [11] BatLevel, [12] SC, [13] GC, [14] OB, [17] CO, [18] VO, [19] PO, 
  [20] PU, [21] CCB 
 from ( 
    select * 
     from [ProductTCPTransaction] 
 ) src 
 PIVOT ( 
    COUNT(TransactionDate) 
    FOR ParameterID 
    in ([1],[2],[4],[5],[6],[8],[9],[10],[11],[12], 
        [13],[14],[17],[18],[19],[20],[21]) 
 ) piv

1 个答案:

答案 0 :(得分:2)

那么怎么样,你可以自己添加其余部分;)

        IF OBJECT_ID('tempdb..#Unpiv') IS NOT NULL DROP TABLE #Unpiv

    CREATE TABLE #Unpiv
    (
        ParameterId int not null,
        ParameterValue varchar(30) not null,
        TransactionDate Date not null
    )

    INSERT INTO #Unpiv
    SELECT 1, '+917506711342', '07/06/16'
    UNION
    SELECT 2, '172500', '07/06/16'
    UNION
    SELECT 4, '310316', '07/06/16'
    UNION
    SELECT 5, 'A', '07/06/16'
    UNION
    SELECT 6, '0', '07/06/16'
    UNION
    SELECT 8, '1', '07/06/16'
    UNION
    SELECT 9, '1', '07/06/16'
    UNION
    SELECT 10, '038', '07/06/16'
    UNION
    SELECT 11, '108', '07/06/16'
    UNION
    SELECT 12, '010', '07/06/16'
    UNION
    SELECT 13, '010', '07/06/16'
    UNION
    SELECT 14, '005', '07/06/16'
    UNION
    SELECT 17, '000', '07/06/16'
    UNION
    SELECT 18, '238', '07/06/16'
    UNION
    SELECT 19, '000', '07/06/16'
    UNION
    SELECT 20, '00000', '07/06/16'
    UNION
    SELECT 21, '00034', '07/06/16'

    SELECT
        [1], [2], [4], [5], [6], [8], [9], [10], [11], [12], [13], TransactionDate
    FROM
        #Unpiv
    PIVOT (MAX(ParameterValue) FOR ParameterId IN ([1], [2], [4], [5], [6], [8], [9], [10], [11], [12], [13])) P