假设我有以下包含事务数据的数据集。以下子集用于说明目的:
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
答案 0 :(得分:2)
在excel中,添加另一行以显示条目的顺序并创建数据透视表:
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
创建一个如下所示的数据透视表:
编辑:对于SQL,请查看Pivot关系运算符来执行此类操作。
答案 1 :(得分:1)
我认为@ ivan7707的解决方案是可行的方法。它利用了Excel的强大功能,甚至可以通过MS Query提供数据集。
那就是说,如果你正在寻找一个强力解决方案,你可以在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
结果: