如何计算 Access table 中的不同记录并在 Excel 中显示该值

How to count distinct records in Access table and display that value in Excel

我在 Access 中有一个 table,我正在从 Excel 查询。我需要有关 sql 语句的帮助。 首先,我需要根据 Where 子句中指示的 SampleType 匹配条件过滤 table。只有 3 个选项:“mel”、“col”或“lun”。最终目标是将所选 SampleType(s) 的 SampleID 列中不同记录的数量传递给一个变量,并将其输出到用户窗体上。 SampleType 列有重复值,需要只计算不同的值。根据我在网上找到的 'COUNT(DISTINCT(' + column_name + ')) 可以,但我不确定如何使用它。

提前感谢您的帮助

Dim var6 As String
Dim var7 As String
Dim var8 As String
var6 = "mel"
var7 =  “lun”
var8 =  “col”
SQLwhere = "WHERE "

If CheckBox5 = True Then
SQLwhere = SQLwhere & "[Table1].[SampleType] LIKE '" & var6 & "%" & "' AND "
‘count a total district records in column SampleID. 
End If

If CheckBox6 = True Then
SQLwhere = SQLwhere & "[Table1].[SampleType] LIKE '" & var7 & "%" & "' AND "
End If

If CheckBox7 = True Then
SQLwhere = SQLwhere & "[Table1].[SampleType] LIKE '" & var & "%" & "' AND "
End If

StrSql = "SELECT * FROM [Table1] "

'Remove the last AND applicable
If SQLwhere = "WHERE " Then
    SQLwhere = ""
Else
    SQLwhere = Left(SQLwhere, Len(SQLwhere) - 5)
End If

StrSql = StrSql & SQLwhere

您的问题比较宽泛,所以答案比较笼统。与MS Access DISTINCT SQL的语法相关,可以是这样的:

SELECT COUNT(*) AS UniqueRecordsCount FROM (SELECT DISTINCT [ColumnName] FROM [SampleTable]) AS T1

或简化为:

SELECT COUNT(*) AS UniqueRecordsCount FROM (SELECT DISTINCT [ColumnName] FROM [SampleTable])

对应您在评论中的补充问题,请看以下内容:

GetDistinctValue = rs("UniqueRecordsCount")

希望这可能有所帮助。