根据不同列中的时间戳对行进行排序和分组

时间:2012-04-09 08:45:30

标签: sql excel vba

我有一张看起来像这样的表

ID Event_A Event_B Event_C
1   01-01
1   01-02 
1           01-05
2   01-02
2                   01-03
3   01-03
3   01-04
3           01-06
3                   01-08

我需要这样的输出

ID Event_1 Event_2 Event_3 Event_4
1   A       A       B
2   A       C
3   A       A       B       C

因此,基本上每个ID都有一行,列中的所有事件类型都按照时间戳(按时间顺序排列)。

任何人都可以建议宏应该如何看待OR sql查询来转换原始表吗?

1 个答案:

答案 0 :(得分:0)

以下是重新格式化数据的VBA例程:

  1. 假设源数据位于活动工作表中,从A1
  2. 开始
  3. F1开始在活动工作表上显示结果 - 根据您的需求进行调整

  4. Sub SummariseList()
        Dim rSrc As Range
        Dim rDst As Range
        Dim vSrc As Variant
        Dim vDst() As Variant
        Dim srcCol As Long, srcRow As Long
        Dim dstCol As Long, dstRow As Long
        Dim ID As Long
        Dim i As Long
    
        Set rSrc = Range([A1].End(xlToRight).Offset(1, 0), [A2].End(xlDown))
        vSrc = rSrc
    
        Set rDst = [F2]
    
        ' Count IDs and events '
        dstRow = 1
        dstCol = 1
        i = 1
        For srcRow = 2 To UBound(vSrc, 1)
            If vSrc(srcRow, 1) = vSrc(srcRow - 1, 1) Then
                i = i + 1
            Else
                dstRow = dstRow + 1
                If dstCol < i Then dstCol = i
                i = 1
            End If
        Next
    
        If dstCol < i Then dstCol = i
        ReDim vDst(1 To dstRow, 1 To dstCol + 1)
    
        ' Output table labels '
        rDst.Offset(-1, 0) = "ID"
        For i = 1 To dstCol
            rDst.Offset(-1, i) = "Event_" & i
        Next
    
        ' Create output data '  
        ID = vSrc(1, 1)
        vDst(1, 1) = ID
        dstRow = 1
        dstCol = 2
        For srcRow = 1 To UBound(vSrc, 1)
            If vSrc(srcRow, 1) <> ID Then
                ' update vDst '  
                ID = vSrc(srcRow, 1)
                dstCol = 2
                dstRow = dstRow + 1
                vDst(dstRow, 1) = ID
            End If
            For srcCol = 2 To UBound(vSrc, 2)
                If vSrc(srcRow, srcCol) <> "" Then
                    vDst(dstRow, dstCol) = Chr(srcCol + 63)
                    dstCol = dstCol + 1
                    Exit For
                End If
            Next
        Next
    
        ' Place result on sheet '
        rDst.Resize(dstRow, dstCol - 1) = vDst
    
    End Sub