Solved

Custom Aggregate Function in MS Access

Posted on 2009-07-10
3
1,029 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 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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How do I partition this table on date? 5 47
SQL Query logic question 14 65
Update Table via VBA SQL with multiple criteria 2 61
Handle Apostrophes in SQL Parameter 16 60
As tax season makes its return, so does the increase in cyber crime and tax refund phishing that comes with it
Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
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…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

738 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