vbaadodb

How to Indicate the Unique Customer ID that not repeated?


I have a set of data and I want to create a calculated field in ADODB query that only states a 'unique' against the customer ID that is not repeated more than once.

Would that wok in select statement?

IIF(COUNT T1.[Customer ID] <> 1 ,Null ,'Unique') as [Unique]
Customer ID Unique
55850
55850
55850
55850
55850
32336
32336
30131 Unique
13914
13914
13914
13914

Solution

  • If you prefer to get the result with ADODB, please try.

    Option Explicit
    Sub ExtractUniqueCustomer()
        Dim conn As Object
        Dim rs As Object
        Dim strSql As String
        Set conn = CreateObject("ADODB.Connection")
        conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & _
            ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
        Set rs = CreateObject("ADODB.Recordset")
        strSql = " SELECT T1.[Invoice], T1.[Customer ID], IIF(T2.[cnt]=1,'Unique','') FROM [Sheet2$] T1 LEFT JOIN " & _
            " (SELECT [Customer ID], COUNT(1) AS cnt FROM [Sheet2$] GROUP BY [Customer ID] HAVING COUNT(1) = 1) T2 " & _
            " ON T1.[Customer ID]=T2.[Customer ID]"
        rs.Open strSql, conn
        ActiveSheet.Cells(2, 1).CopyFromRecordset rs
        rs.Close
        Set rs = Nothing
        conn.Close
        Set conn = Nothing
    End Sub
    
    

    [1]: https://i.sstatic.net/xlLB9.png