Improve company productivity with a Business Account.Sign Up

x
?
Solved

Access Highest Date Query

Posted on 2009-03-29
11
Medium Priority
?
909 Views
Last Modified: 2013-11-27
Hi,
Im probably being pretty dumb here but I wonder if somebody can answer me this quickly.

Given a table with a number of date fields in it i.e.
DATE1 DATE2 DATE3 DATE4

They may or may not have any data entered for some or all fields and can also be NULL how would I run a query to loop through each record and display the value of the highest date present in a Fifth field like this.

DATE1 DATE2 DATE3 DATE4 HIGHESTDATE

I tried playing around with MAX etc but cant seem to get anywhere and running out of time.
0
Comment
Question by:ddglas
  • 4
  • 2
  • 2
  • +2
11 Comments
 
LVL 4

Expert Comment

by:dublingills
ID: 24013587
You can't compare using max as max is used on the same field across different records.  You need to compare the value of each field using one of:

1.  Iif - you'll need to nest these.
or
2. If you are ok with writing VBA you can use a VBA function in a module, something like:

function MaxDate(date1 as date, date2 as date, date3 as date, date4 as date)
dim result as date
if date1 > date2 then result = date1 else result = date2
if date3 > result then result = date3
if date4 > result then result = date4
maxdate = result
end function

The VBA method is by far the easiest.

HTH
0
 
LVL 75
ID: 24013592
something like this:

SELECT Table1.DATE1 , Table1.DATE2 , Table1.DATE3 ,   Table1.DATE2,  (SELECT Max([HIGHESTDATE]) AS MaxDate FROM Table1;) AS Expr1
FROM Table1;
0
 
LVL 93

Accepted Solution

by:
Patrick Matthews earned 1000 total points
ID: 24013659
Hello ddglas,

You could suss this out using Switch() or nested IIf(), but like dublingills I would be inclined to use a UDF
to give the appearance of a cleaner expression.

The UDF below is highly flexible, allowing you to calculate a min, max, or avg, for any number of inputs
(up to the limit for a ParamArray, which I think is 31).  You can also pass text, dates, or numbers as
the arguments.  (If you pass dates or non-numbers when the type is "avg", they get ignored in computing
the average.)

Use the function like this:

SELECT Date1, Date2, Date3, Date4, RowStats("Max", Date1, Date2, Date3, Date4) AS MaxDate
FROM SomeTable

Regards,

Patrick
Function RowStats(Stat As String, ParamArray Vars())
    
    Dim Numerator As Double
    Dim Denominator As Double
    Dim Counter As Long
    Dim Result
    
    Select Case UCase(Stat)
        Case "MIN"
            Result = Vars(LBound(Vars))
            For Counter = LBound(Vars) + 1 To UBound(Vars)
                If Vars(Counter) < Result Then Result = Vars(Counter)
            Next
        Case "MAX"
            Result = Vars(LBound(Vars))
            For Counter = LBound(Vars) + 1 To UBound(Vars)
                If Vars(Counter) > Result Then Result = Vars(Counter)
            Next
        Case "AVG"
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then
                    Numerator = Numerator + Vars(Counter)
                    Denominator = Denominator + 1
                End If
            Next
            Result = Numerator / Denominator
    End Select
    
    RowStats = Result
    
End Function

Open in new window

0
Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

 
LVL 59
ID: 24013667
The problem you have is that this is not a normalized table, so you simply won't be able to use MAX() (each of those date fields should be in a seperate record in a related table).
There are a couple of approaches.  You can use a bunch of IIF's in the query itself (difficult to debug), call a custom function passing all the dates and returning the highest, or do this in code.  I think what you be best is a custom function.  Paste the following into a general module:

Function GetHighestDate(varDate1 As Variant, varDate2 As Variant, varDate3 As Variant, varDate4 As Variant) As Variant
  If IsNull(varDate1) And IsNull(varDate2) And IsNull(varDate3) And IsNull(varDate4) Then
    GetHighestDate = Null
  Else
    GetHighestDate = Nz(varDate1, 0)
    If Nz(varDate2, 0) > GetHighestDate Then GetHighestDate = varDate2
    If Nz(varDate3, 0) > GetHighestDate Then GetHighestDate = varDate3
    If Nz(varDate4, 0) > GetHighestDate Then GetHighestDate = varDate4
  End If
End Function
  In your query, define a column as HighestDate:GetHighestDate([<datefieldname1>],[<datefieldname2>],[<datefieldname3>],[<datefieldname4>]
  replacing (and including) everything with <> with the actual names of your date fields.
JimD.
0
 
LVL 75
ID: 24013676
I'm reading this different:

"and display the value of the highest date present in a Fifth field"
                                                                                 ^^^^^^^^^^^^^

mx
0
 
LVL 59
ID: 24013694
Patrick's deal is slick...I like it<g>.  Got this one bookmarked.  Best generic approach to handling a non-normalized table problem like this that I've seen yet.
JimD.
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 24013727
Jim,

Thanks for the compliment!  BTW, here is an expanded version, which also handles standard deviation
(sample and population) and variance (sample and population).

Regards,

Patrick
Function RowStats(Stat As String, ParamArray Vars())
    
    Dim Numerator As Double
    Dim Denominator As Double
    Dim Counter As Long
    Dim Result
    
    Stat = UCase(Stat)
    
    Select Case Stat
        Case "MIN"
            Result = Vars(LBound(Vars))
            For Counter = LBound(Vars) + 1 To UBound(Vars)
                If Vars(Counter) < Result Then Result = Vars(Counter)
            Next
        Case "MAX"
            Result = Vars(LBound(Vars))
            For Counter = LBound(Vars) + 1 To UBound(Vars)
                If Vars(Counter) > Result Then Result = Vars(Counter)
            Next
        Case "AVG"
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then
                    Numerator = Numerator + Vars(Counter)
                    Denominator = Denominator + 1
                End If
            Next
            Result = Numerator / Denominator
        Case "STDEV", "STDEVP", "VAR", "VARP"
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then
                    Numerator = Numerator + Vars(Counter)
                    Denominator = Denominator + 1
                End If
            Next
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then Result = Result + (Vars(Counter) - (Numerator / Denominator)) ^ 2
            Next
            Result = Result / IIf(Stat Like "*P", Denominator, Denominator - 1)
            If Stat Like "S*" Then Result = Result ^ 0.5
    End Select
    
    RowStats = Result
    
End Function

Open in new window

0
 
LVL 1

Author Comment

by:ddglas
ID: 24013808
Im getting undefined function "Rowstats" when trying to run that, any idea what i've done wrong.

I have copied the function in.
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 24013846
ddglas,

Make sure that you placed the UDF in a regular module, and not a form/report/class module.  Also make
sure that that module is not using an Option Private Module declaration.  Do a debug/compile from the
VBA Editor, and check your macro security setting.

Regards,

Patrick
0
 
LVL 1

Author Closing Comment

by:ddglas
ID: 31564075
Thanks a Million, very useful
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 24013916
ddglas,

Glad to help.  BTW, here is a final version.  The version I posted at first has a flaw in the min and max calculations:
if the first element in the array is null, the result comes back null.  The version below fixes that flaw, and is also
documented.

Regards,

Patrick
Function RowStats(Stat As String, ParamArray Vars())
    
    ' Function by Patrick Matthews
    
    ' This Access UDF calculates various stats for the values passed into the ParamArray.  It
    ' was originally designed for passing several values from a particular row set for
    ' evaluation; since the values come from the same row, the usual aggregate functions would
    ' not be appropriate.
    
    ' The Stat variable (NOT case sensitive) determines what statistic is calculated:
    ' "min", "max":     minimum or maximum
    ' "sum", "avg":     sum or average, excluding dates or strings
    ' "var", "stdev":   sample variance or standard deviation (excluding dates or strings)
    ' "varp", "stdevp": sample variance or standard deviation (excluding dates or strings)
    
    ' You may pass any value in the ParamArray.  Strings, nulls, and dates are ignored for the
    ' sum, avg, stdev, stdevp, var, and varp calculations.  (Thus, you could use this function to
    ' add several columns together without wrapping each column with Nz() to handle nulls...)
    
    Dim Numerator As Double
    Dim Denominator As Double
    Dim Counter As Long
    Dim Result
    
    ' Force to upper case to make sure string comparisons are always performed as expected;
    ' Access uses Option Compare Database by default, but other VBA/VB6 uses binary default
    
    Stat = UCase(Stat)
    
    Select Case Stat
        Case "MIN"
        
            ' Set the result to the first value in the array, then check the other values in
            ' turn to see if it is less.
            
            Result = Vars(LBound(Vars))
            For Counter = LBound(Vars) + 1 To UBound(Vars)
                If IsNull(Result) And Not IsNull(Vars(Counter)) Then
                    Result = Vars(Counter)
                ElseIf Vars(Counter) < Result Then
                    Result = Vars(Counter)
                End If
            Next
        
        Case "MAX"
            
            ' Set the result to the first value in the array, then check the other values in
            ' turn to see if it is greater.
            
            Result = Vars(LBound(Vars))
            For Counter = LBound(Vars) + 1 To UBound(Vars)
                If IsNull(Result) And Not IsNull(Vars(Counter)) Then
                    Result = Vars(Counter)
                ElseIf Vars(Counter) > Result Then
                    Result = Vars(Counter)
                End If
            Next
            
        Case "AVG", "SUM"
        
            ' Check each value in turn.  If it is numeric, then increment numerator and denominator.
            ' Divide numerator by denominator to get an average, or by 1 to get the sum
            
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then
                    Numerator = Numerator + Vars(Counter)
                    Denominator = Denominator + 1
                End If
            Next
            Result = Numerator / IIf(Stat = "AVG", Denominator, 1)
        
        Case "STDEV", "STDEVP", "VAR", "VARP"
        
            ' Take one pass through the set to determine the average, and then determine the
            ' sum of squared deviances from the mean.  Divide by number of elements in the
            ' array for population or (elements - 1) for sample.  If standard deviation,
            ' take square root
            
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then
                    Numerator = Numerator + Vars(Counter)
                    Denominator = Denominator + 1
                End If
            Next
            For Counter = LBound(Vars) To UBound(Vars)
                If IsNumeric(Vars(Counter)) Then Result = Result + (Vars(Counter) - (Numerator / Denominator)) ^ 2
            Next
            Result = Result / IIf(Stat Like "*P", Denominator, Denominator - 1)
            If Stat Like "S*" Then Result = Result ^ 0.5
    End Select
    
    RowStats = Result
    
End Function

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

What to do if a split doesn't fit? Or a bunch of invoice lines must be rounded while the sum must match a total? It takes a little, but - when done - it is extremely easy to implement.
The best software application must always have an error handling tool
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
A query can call a function, and a function can call Excel, even though we are in Access. This is Part 2, and steps you through the VBA that "wraps" Excel functionality so we can use its worksheet functions in Access. The declaration statement de…

580 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