枢轴多列和多行

时间:2018-05-02 15:28:29

标签: sql sql-server

这是我的原始数据:

ID New LikeNew Old  Warehouse
1  10  100     20   LA
1  12  130     40   CA
2  90  200     10   LA
2  103 230     30   CA

我想获得以下格式:

ID LA_new LA_likeNew LA_Old CA_New CA_LikeNew CA_Old  
1  10     100        20     12     130        40
2  90     200        10     103    230        30

我只能在每一列上进行旋转,但不能在所有3列(New,LikeNew,Old)上进行操作,那么我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

您可以使用条件逻辑来创建字段和分组来完成此任务:

    Sheets("Interface Catalogue").Select
    Dim UniqID As String
    UniqID = Trim(ActiveCell.Value)


    Sheets("Data Elements").Select
    LastB = Cells(Rows.Count, "B").End(xlUp).Row
    LastA = Cells(Rows.Count, "A").End(xlUp).Row
    If LastA > LastB Then
            Range("A" & Rows.Count).End(xlUp).Offset(10).Select
            Selection.Formula = "=HYPERLINK(""#""&CELL(""address"",INDEX('Interface Catalogue'!F:F,MATCH(""& UniqID &"",'Interface Catalogue'!F:F,0))),""& UniqID &"")"
        Else
            Range("B" & Rows.Count).End(xlUp).Offset(2).Previous.Select
            Selection.Formula = "=HYPERLINK(""#""&CELL(""address"",INDEX('Interface Catalogue'!F:F,MATCH(""& UniqID &"",'Interface Catalogue'!F:F,0))),""& UniqID &"")"

        End If
End Sub

答案 1 :(得分:0)

或者,您可以使用WITH Common Table Expression

       DECLARE @T AS TABLE
        (
          id INT ,
          New INT ,
          likeNew INT ,
          old INT ,
          Warehouse VARCHAR(50)
        )

       INSERT   INTO @T
                ( id, New, likeNew, old, Warehouse )
       VALUES   ( 1, 10, 100, 20, 'LA' ),
                ( 1, 12, 130, 40, 'CA' ),
                ( 2, 90, 200, 10, 'LA' ),
                ( 2, 103, 230, 30, 'CA' );
       WITH cte
              AS ( SELECT   *
                   FROM     @T
                   WHERE    Warehouse = 'LA'
                 ),
            cte1
              AS ( SELECT   *
                   FROM     @T
                   WHERE    Warehouse = 'CA'
                 )
        SELECT  a.id ,
                a.new [LA_New] ,
                a.likeNew [LA_LikeNew] ,
                a.Old [LA_Old] ,
                b.new [CA_New] ,
                b.likeNew [CA_LikeNew] ,
                b.Old [CA_Old]
        FROM    cte A
                JOIN cte1 B ON a.id = b.id

结果:

    id          LA_New      LA_LikeNew  LA_Old      CA_New      CA_LikeNew  CA_Old
    ----------- ----------- ----------- ----------- ----------- ----------- -----------
    1           10          100         20          12          130         40
    2           90          200         10          103         230         30