select greater of 2 values

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need to add an expression to a select query that returns the greatest of
several values - like the MAX(a,b,c) function in Excel.

For example, I need to be able to create the "MaxSales" field by saying
MAX(WestSales, EastSales)

Rep WestSales East Sales MaxSales
Smith 100 50 100
Jones 90 200 200

How do I do this in an SQL statement?
(I can't use an iif statement because I need to select from several fields
and calculated values and iif just won't work)

Any help is appreciated.
 
crashix said:
I need to add an expression to a select query that returns the greatest of
several values - like the MAX(a,b,c) function in Excel.

For example, I need to be able to create the "MaxSales" field by saying
MAX(WestSales, EastSales)

Rep WestSales East Sales MaxSales
Smith 100 50 100
Jones 90 200 200

How do I do this in an SQL statement?
(I can't use an iif statement because I need to select from several fields
and calculated values and iif just won't work)


There's no built in way to do that. That's because the
normalization rules of relational databases say that you
should not have fields like that. Instead, you should have
more tables with simpler records that you can max a set of
records, not a set of columns.

If you're stuck with your speadsheet style tables, then
here's a function will do what you asked:

Public Function MaxOfList(ParamArray vValues() As Variant)
As Variant
Dim vX As Variant

MaxOfList = vValues(0)
For Each vX In vValues
If vX > MaxOfList Then MaxOfList = vX
Next vX
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top