具有重复条目筛选的Microsoft Access的不同计数

时间:2016-10-26 22:12:33

标签: sql vba ms-access ms-access-2016

我正在处理微软访问的查询,需要计算数据库中sold_quotes的数量,但过滤掉重复的数据库条目。

我已尝试实施DCount表达式来处理它,

Sold Status: DCount("idquote","Quote","sold_status = '1'")

我们的想法是计算idquote条目的数量,其中sold_status等于1。

我们甚至尝试过一种自定义的VBA模块,它可以稍微区别地处理DistinctCount,但这并没有产生预期的答案。

Function DCountDistinct(CountCols As String, Tbl As String, Optional Criteria As String = "")

' Function by Patrick G. Matthews

' Requires reference to Microsoft DAO library

' This function provides "domain aggregate"-type functionality similar to
' COUNT(DISTINCT ColumnName) in Transact-SQL (i.e., SQL Server's dialect).  The function
' can be used in queries, forms, and reports in the Access UI and/or in VBA code once added
' to a regular VBA module

' CountColumns is a comma-delimited list of columns for which we are counting the distinct
'   values (or combinations of values if 2+ columns are specified).  Place field names in
'   square brackets if they do not meet the customary rules for naming DB objects
' Tbl is the table/query the data are pulled from.  Place table name in square brackets
'   if they do not meet the customary rules for naming DB objects
' Criteria (optional) are the criteria to be applied in the grouping.  Be sure to use And
'   or Or as needed to build the right logic, and to encase text values in single quotes
'   and dates in #

' Just like DCount, if there are no items found matching the criteria, DCountDistinct
' returns zero

Dim rs As DAO.Recordset
Dim SQL As String

' Enable error handler

On Error GoTo ErrHandler

' Build query that counts the number of distinct items (or combinations of items, if
' CountCols specifies 2+ columns) that meet the specified criteria.  If no criteria are
' specified, then count goes against entire table

SQL = "SELECT Count(1) AS Result " & _
    "FROM (" & _
        "SELECT DISTINCT " & CountCols & " " & _
        "FROM " & Tbl & " " & _
        IIf(Criteria <> "", "WHERE " & Criteria, "") & _
    ")"

' Open recordset with result

Set rs = CurrentDb.OpenRecordset(SQL)

' Set return value

DCountDistinct = rs!Result

rs.Close

GoTo Cleanup

ErrHandler:
    DCountDistinct = CVErr(Err.Number)

Cleanup:
    Set rs = Nothing

End Function

但由此产生的结果并没有按预期发挥作用,也没有计算正确的副本。

有什么想法吗?

继承查询的SQL

SELECT DCount("idquote","Quote","sold_status = '1'") AS [Sold Status]
FROM Quote
WHERE (((Quote.sold_status)="1"))
GROUP BY DCount("idquote","Quote","sold_status = '1'")
HAVING (((DCount("idquote","Quote","sold_status = '1'"))=1));

0 个答案:

没有答案