Solved

Custom Aggregate Function in MS Access

Posted on 2009-07-10
3
955 Views
Last Modified: 2013-11-27
OK, I know aggregate functions MIN(...), AVG(...), SUM(...).
How can I write PROD(...) function that is similar to SUM?

         x1 + x2 + ... + xN
but computes product
         x1 * x2 *... xN

SELECT sum(salary), prod(rate) from whateverTable group by depID
0
Comment
Question by:midfde
3 Comments
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 24828166
Take a look at this:
http://www.access-programmers.co.uk/forums/showthread.php?t=141914

The gist is to create your function to take in deptID for example, so usage like this:
SELECT sum(salary), prod(depID) from whateverTable group by depID

Or to make it more flexible, pass in tablename, columnname and where filters or just pass sql string itself.

Code sample below.  You would just keep multiplying by each rate you find in loop and then return.


Dim strSQL  As String

Dim db      As DAO.Database

Dim rs      As DAO.Recordset
 

  Set db = CurrentDb()

  

  strSQL = "SELECT ..." 

  Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
 

  Do While Not rs.EOF

    'do your thing

    rs.MoveNext

  Loop
 

  set rs = nothing

  set db = nothing

Open in new window

0
 
LVL 92

Accepted Solution

by:
Patrick Matthews earned 500 total points
ID: 24830415
Hello midfde,

The UDF below, when placed in a regular VBA module, seems to be working.  Since the behavior is similar
to the "domain aggregate" functions, I named it DProd.

Some caveats:

1) If any of the factors that are being multiplied are Null, then the result will be Null.  If you want a zero
in this instance, just wrap the expression in Nz.

2) As with regular multiplication, if any of the factors are zero, the result will be zero

3) The function seems to be doing an implicit conversion to Double.  I tested it by passing a Long field
with vaues that would produce:
1 * 2 * 3 * ... * 100
which would, of course, exceed the ~2.1 billion limit for Long.  The answer I got back was ~9.3 x 10^157.
If you are passing the result to a variable or a column of type Integer or Long, just be aware that you
could get an overflow error if the factors are too big

You would use it like this:

SELECT depID, Sum(salary) AS TotSalary, DProd("[rate]", "[SomeTable]", "[depID] = " & [depID]) AS ProdRate
FROM SomeTable
GROUP BY depID

If depID is not numeric...

SELECT depID, Sum(salary) AS TotSalary, DProd("[rate]", "[SomeTable]", "[depID] = '" & [depID] & "'") AS ProdRate
FROM SomeTable
GROUP BY depID


Regards,

Patrick
Function DProd(FieldName As String, TableName As String, Optional Criteria As String = "")
    
    Dim SQL As String
    Dim rs As DAO.Recordset
    
    FieldName = "[" & Replace(Replace(FieldName, "[", ""), "]", "") & "]"
    TableName = "[" & Replace(Replace(TableName, "[", ""), "]", "") & "]"
    
    SQL = "SELECT " & FieldName & " FROM " & TableName
    If Criteria <> "" Then SQL = SQL & " WHERE " & Criteria
    
    Set rs = CurrentDb.OpenRecordset(SQL)
    
    If rs.EOF Then
        Prod = Null
    Else
        Prod = 1
        Do While Not rs.EOF
            Prod = Prod * rs.Fields(0)
            rs.MoveNext
        Loop
    End If
    
    rs.Clone
    Set rs = Nothing
    
End Function

Open in new window

0
 
LVL 1

Author Closing Comment

by:midfde
ID: 31602310
Thanks. I wonder what about custom aggregate functions in SQL Server environment
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article is a continuation or rather an extension from Cascading Combos (http://www.experts-exchange.com/A_5949.html) and builds on examples developed in detail there. It should be understandable alone, but I recommend reading the previous artic…
Introduction The Visual Basic for Applications (VBA) language is at the heart of every application that you write. It is your key to taking Access beyond the world of wizards into a world where anything is possible. This article introduces you to…
In Microsoft Access, learn the trick to repeating sub-report headings at the top of each page. The problem with sub-reports and headings: Add a dummy group to the sub report using the expression =1: Set the “Repeat Section” property of the dummy…
With Microsoft Access, learn how to specify relationships between tables and set various options on the relationship. Add the tables: Create the relationship: Decide if you’re going to set referential integrity: Decide if you want cascade upda…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now