find the first 2 highest values from a record (1 Viewer)

RK1

New member
Local time
Today, 07:34
Joined
Nov 17, 2017
Messages
3
Dear All,

I have a table with 3 fields and I would like to insert a forth and fifth field that would calculate the max and 2nd highest value for each record (I mean the max 2 values out of the three fields)

Eg.
Field1---Field2---Field3---Newfield1------- Newfield2
2---------3------- 4------------4---------------3
5---------6---------5-------------6---------------5
6---------6---------3------------6---------------6

Could you please help me how to achieve that?

Many thanks!!
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 22:34
Joined
May 7, 2009
Messages
19,233
copy and paste the functions in Standard Module:
Code:
public function fnMax1(p1,p2,p3) as variant
fnMax1=p3
if p1>p2 and p1>p3 then fnMax1=p1: exit function
if p2>p1 and p2>p3 then fnMax1=p2
end function

Public Function fnMax2(p1, p2, p3)
fnMax2 = p3
If p1 > p2 And p1 < p3 Or p1 > p3 And p1 < p2 Then fnMax2 = p1: Exit Function
If p2 > p1 And p2 < p3 Or p2 > p3 And p2 < p1 Then fnMax2 = p2
End Function


to use in Simple Select Query:


select field1, field2, field3, fnMax1(field1,field2,field3) As NewField1, fnMax2(field1,field2,field3) As NewField2 from yourTable;



to update Newfield1, NewField2 in the table using Update query:


Update yourTable set NewField1=fnMax1(field1,field2,field3), NewField2=fnMax2(field1,field2,field3);
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 10:34
Joined
Feb 19, 2002
Messages
43,224
Access has no function to do this because the repeating group violates first normal form. What you have is essentially a spreadsheet and you will find that Excel is much better suited to working with spreadsheets than a real relational database tool such as Access is.

To normalize the table, you would create a separate table that contains one row for each of the repeating columns. In a properly normalized schema, adding the two additional values would not change any query, form, or calculation. Please note that you will have to modify the suggested UDF to increase the argument count each time you add additional arguments.

The query would be:
Select Top 2 SomePKfield, DataField
From YourTable
Order By DataField Desc;
 

RK1

New member
Local time
Today, 07:34
Joined
Nov 17, 2017
Messages
3
Thanks sir , I was able to get the answer. I made a small modification . I used = along with > and < sign in first line in both the functions.
 

isladogs

MVP / VIP
Local time
Today, 15:34
Joined
Jan 14, 2017
Messages
18,209
I'm just curious ...
If you used all three operators, < and > and = in Ariel's code, won't it always exit the function at that line?
 

Users who are viewing this thread

Top Bottom