如何正确使用Unpivot

时间:2018-02-27 21:15:03

标签: sql-server unpivot

我是SQL的初学者。我想将一些列转换为视图中的行,这是我的观点:

SLPRSNID    ITEMNMBR        1       2       3     4     5
1           01-GOGUA-010    0       500     500   500   500
4           01-GOGUA-020    1850    3850    2350  4450  2450

我需要:

SLPRSNID    ITEMNMBR        VOLUME
1           01-GOGUA-010    2000
4           01-GOGUA-020    14950

我用过:

SELECT ITEMNMBR, VOLUMEN
FROM dbo.SOPPPTOVOL
UNPIVOT
(
    VOLUMEN
    FOR ITEMNMBR IN ([1], [2], [3], [4], [5]) 
) AS UnPvt

但它没有用。

1 个答案:

答案 0 :(得分:0)

  1. 使用APPLY

    DECLARE @table table (
    SLPRSNID INT ,
    ITEMNMBR VARCHAR(50),
    [1] FLOAT,
    [2] FLOAT,
    [3] FLOAT,
    [4] FLOAT,
    [5] FLOAT
    )
    
    INSERT INTO @table 
     VALUES (1, '01-GOGUA-010', 0.00,500.00,500.00,500.00,500.00),
            (4, '01-GOGUA-020', 1850.0,3850.00,2350.00,4450.00,2450.00)
    
    
    SELECT T.SLPRSNID,T.ITEMNMBR, P.VOLUME
    FROM @table T
      CROSS APPLY 
            (
             SELECT SUM(X.VAL)
             FROM
                (
                 VALUES  ([1]),([2]),([3]),([4]),([5])  
                ) X(VAL)
            ) P(VOLUME)
    
  2. 使用UNPIVOT

    DECLARE @table table (
    SLPRSNID INT ,
    ITEMNMBR VARCHAR(50),
    [1] FLOAT,
    [2] FLOAT,
    [3] FLOAT,
    [4] FLOAT,
    [5] FLOAT
    )
    
    INSERT INTO @table 
    VALUES (1, '01-GOGUA-010', 0.00,500.00,500.00,500.00,500.00),
           (4, '01-GOGUA-020', 1850.0,3850.00,2350.00,4450.00,2450.00)
    
    SELECT E.SLPRSNID , E.ITEMNMBR , SUM(E.VOL) VOLUME
    FROM @table T 
        UNPIVOT 
            (
            VOL FOR VALS IN ([1],[2],[3],[4],[5]) 
            ) E
    GROUP BY  E.SLPRSNID , E.ITEMNMBR