[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Custom Aggregate Function in MS Access

Posted on 2009-07-10
3
Medium Priority
?
1,147 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 60

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 93

Accepted Solution

by:
Patrick Matthews earned 2000 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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

Did you know that more than 4 billion data records have been recorded as lost or stolen since 2013? It was a staggering number brought to our attention during last week’s ManageEngine webinar, where attendees received a comprehensive look at the ma…
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
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…

649 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