我有一组数据,我想在 ADODB 查询中创建一个计算字段,该字段仅针对不会重复多次的客户 ID 声明“唯一”。
这在 select 语句中行得通吗?
IIF(COUNT T1.[Customer ID] <> 1 ,Null ,'Unique') as [Unique]
客户ID | 独特 |
---|---|
55850 | |
55850 | |
55850 | |
55850 | |
55850 | |
32336 | |
32336 | |
30131 | 独特 |
13914 | |
13914 | |
13914 | |
13914 |
请使用下一个代码。假设 ID 列是 A:A。
使用数组和字典,主要在内存中工作,即使要处理很大的范围,它也应该非常快:
Sub UniqueUnique()
Dim sh As Worksheet, lastR As Long, arr, i As Long, dict As Object
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).Row 'last row in A:A
arr = sh.Range("A2:B" & lastR).Value2 'place the range in an array for faster processing
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr)
If Not dict.Exists(arr(i, 1)) Then
dict.Add arr(i, 1), i 'place the row where the ID has been found first time
Else
dict(arr(i, 1)) = vbNullString 'delete the row number if more than one occurrence
End If
Next i
'process the dictionary
For i = 0 To dict.count - 1
If dict.Items()(i) <> vbNullString Then arr(dict.Items()(i), 2) = "Unique"
Next i
'drop back the processed array:
sh.Range("A2").Resize(UBound(arr), UBound(arr, 2)).Value2 = arr
End Sub
请测试并发送一些反馈。
如果有不清楚的地方,即使我对每一行都进行了评论,请随时要求澄清。