查找唯一的行集

时间:2010-11-10 15:51:02

标签: ms-access vba access-vba

我在Access 2003中有一个包含以下字段的表

Ptr_RateTable
MinOfWeight_Up_To
Adder

我需要为任何表找到MinOfWeight_Up_To的唯一值,而不在结果中显示表名。我试图通过查找可以在相同的重量中断时压缩的表格来压缩大型机中的表格大小。

所以例如

Ptr_RateTable|MinOfWeight_Up_To
1109LW020|1.00
1109LW020|2.00
1109LW020|6.00
1109LW020|11.00
1109LW020|101.00
1109LW020|128.00
1109LW020|129.00
1109LW021|1.00
1109LW021|2.00
1109LW021|3.00
1109LW021|11.00
1109LW021|36.00
1109LW021|41.00
1109LW021|151.00

我希望看到以下结果,而不是制作具有相同重量值的另一个“个人资料”

Profile1|1.00|2.00|6.00|11.00|101.00|128.00|129.00
Profile2|1.00|2.00|3.00|11.00|36.00|41.00|151.00

2 个答案:

答案 0 :(得分:0)

首先,您需要一个为该表生成签名的函数。类似于:

Public Function GetSignature(sTableName As String) As String

Dim oDB As DAO.Database
Dim oRS As DAO.Recordset
Dim sSQL As String
Dim sResult As String

sSQL = "Select Distinct MinOfWeight_Up_To" _
    & vbCrLf & "From [" & sTableName & "]"
    & vbCrLf & "Order By MinOfWeight_Up_To"

Set oDB = DBEngine.Workspaces(0).Databases(0)
Set oRS = oDB.OpenRecordset(sSQL, dbOpenForwardOnly, dbReadOnly)

Do Until oRS.EOF
    sResult = sResult & "|" & Nz(oRS(0))
    oRS.MoveNext
Loop

GetSignature = result

Set oRS = Nothing
Set oDB = Nothing

End Function

一旦有了这个,就需要另一个例程来组装表的列表,为每个表调用上面的签名并将结果存储在临时表中。然后,您将查询该临时表以获取唯一的签名列表。

应该注意的是,字符串连接的数量非常慢。相反,您应该寻找可用于构建签名的更高效的字符串构建器类的实现。

答案 1 :(得分:0)

使用交叉表查询:

Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection

Set cn = CurrentProject.Connection

sSQL = "TRANSFORM Min(s.MinOfWeight_Up_To) AS Min_Weight " _
& "SELECT 'Profile' & Right([Ptr_RateTable],2) AS Profile " _
& "FROM Sample s " _
& "GROUP BY s.Ptr_RateTable " _
& "PIVOT s.MinOfWeight_Up_To"

rs.Open sSQL, cn

astr = rs.GetString
Do While InStr(astr, Chr(9) & Chr(9)) > 0
    astr = Replace(astr, Chr(9) & Chr(9), Chr(9))
Loop

Debug.Print astr