Skip to content
Advertisement

How to SQL join tables, selecting the largest value in Access-VBA Function?

I currently have the following Access VBA function, which operates as explained in a previous question (very useful for understanding this question):

However, instead of Field3 containing either yes or no, in my data it can contain one of several values. For simplicity, let’s say that these values can be any one item from the following set of strings:
(0, >1 million, 0001-0010)

In this case, the Max() Access SQL function will not work on Field3 since they’re strings with a user-defined hierarchy. Yet, I need the largest value to still be selected. I will define the values from lowest (1) to highest (3):

  1. 0
  2. >1 million
  3. 0001-0010

Here is an example of how tableNameTemp may appear:

And given the example tableNameTemp values above, the table below shows how those values would be mapped onto the tableName table. Notice how it picks the largest value to map.

As I am neither highly experienced with Access SQL nor VBA, I am at a loss as to how I can make this happen. I’m guessing it may involve hard-coding a list of the possible values for Field3, then ranking them based on their position in the list (i.e. position 3 would contain the value 0). Then, somehow using this as a key for which value to pick. If this is of any use, I have provided the code for it below:

EDIT
Updated code, as per Serg’s help:

Advertisement

Answer

Encode value, decode max this way in SQL.

Currently you are building SQL command as (i replaced table name variables with arbitrary values, temp and tableName )

Build it as

So [field3] is encoded under max() in the inner query and that max is decoded in outer query.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement