在单个行上进行组交易

假设我有以下数据集包含交易数据。 下面的子集用于说明目的:

BillName Item Number Customer A 477565 Customer A 8400212 Customer A 8400213 Customer A 461230 Customer A 461240 Customer A 477545 Customer A 8657915 Customer B 672050 Customer B 892223 Customer C 640741 Customer C 640772 Customer C 640660 

如何使用Excel或SQL Server将它转换为如下所示?

 Customer A 477565 8400212 8400213 461230 461240 477545 8657915 Customer B 672050 892223 Customer C 640741 640772 640660 

在Excel中,添加另一行以显示条目的顺序并创build一个数据透视表:

BillName组项目编号优先顺序

 BillName group Item Number precedence Customer A 477565 1 Customer A 8400212 2 Customer A 8400213 3 Customer A 461230 4 Customer A 461240 5 Customer A 477545 6 Customer A 8657915 7 Customer B 672050 1 Customer B 892223 2 Customer C 640741 1 Customer C 640772 2 Customer C 640660 3 

创build一个如下所示的数据透视表:

在这里输入图像说明

或以所有标签重复的forms 在这里输入图像说明

编辑:对于SQL,看看枢轴关系运算符做这种事情。

我认为@ ivan7707的解决scheme是要走的路。 它利用Excel的强大function,甚至可以通过MS Query将数据集引入。

也就是说,如果你正在寻找一个蛮力的解决scheme,你可以在VBA中这样做:

 Dim Conn As New ADODB.Connection Dim cmd As ADODB.Command Dim rs As ADODB.Recordset Dim bill, item, priorBill As String Dim row, col As Integer Dim ws As Worksheet Set ws = ActiveWorkbook.ActiveSheet Conn.Open "Your Connection String" Set rs = Conn.Execute("select bill_name, item_number from bills order by 1") row = 1 col = 2 Do While Not rs.EOF bill = rs.Fields(0).Value item = rs.Fields(1).Value If bill <> priorBill Then row = row + 1 col = 2 ws.Cells(row, 1).Value = bill priorBill = bill End If ws.Cells(row, col).Value = item col = col + 1 rs.MoveNext Loop Conn.Close 

结果:

在这里输入图像说明