【问题标题】:How to count distinct records in Access table and display that value in Excel如何计算 Access 表中的不同记录并在 Excel 中显示该值
【发布时间】:2015-06-28 02:26:40
【问题描述】:

我在 Access 中有一个要从 Excel 查询的表。我需要有关 sql 语句的帮助。 首先,我需要根据 Where 子句中指示的 SampleType 匹配条件过滤表。只有 3 个选项:“mel”、“col”或“lun”。最终目标是将所选 SampleType(s) 的 SampleID 列中不同记录的数量传递给变量并将其输出到 UserForm 上。 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

【问题讨论】:

  • 您实际上是在以一种不清楚的方式提出多个问题。请缩小您的帖子范围并突出显示您要解决的关键问题。最好的问候,

标签: sql excel vba ms-access subquery


【解决方案1】:

您的问题相当广泛,所以答案有点笼统。与 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])

对应你在cmets的附加问题,请看以下内容:

GetDistinctValue = rs("UniqueRecordsCount")

希望这会有所帮助。

【讨论】:

  • 感谢 Alex,据我了解,我需要将 "SELECT * FROM [Table1] " 替换为 SELECT COUNT(*) FROM (SELECT DISTINCT [ColumnName] FROM [SampleTable])。打开记录集后,如何将该值传递给变量? Set rs = New ADODB.Recordset rs.Open sql, cnn GetDistinctValue = rs.? 非常感谢您的帮助
  • 不客气。我已经扩展了与您的附加问题相关的答案。如果满意,请标记为已接受。如果您有更多问题,请单独发布。祝你的项目好运。最好的问候,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 2019-09-26
相关资源
最近更新 更多