Solved

Custom Aggregate Function in MS Access

Posted on 2009-07-10
3
930 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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

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…
A simple tool to export all objects of two Access files as text and compare it with Meld, a free diff tool.
Learn how to number pages in an Access report over each group. Activate two pass printing by referencing the pages property: Add code to the Page Footers OnFormat event to capture the pages as there occur for each group. Use the pages property to …
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

759 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

20 Experts available now in Live!

Get 1:1 Help Now