0

looking TO GET THE MAX() VALUE from a table like the one below. Here is what the table looks like

LEVEL  ACCOUNTNAME
0.11      namea
1.25      namea
14.55     namea
3.52      namea

HER IS THE CODE THAT I USE:

SELECT 
MAX(LEVEL) AS HIGHESTLEVEL, ACCOUNTNAME
FROM TABLE
GROUP BY ACCOUNTNAME

however my returned answer is

LEVEL    ACCOUNTNAME
3.52        namea

I should be getting 14.55 not 3.52. anyone know what is going on?

2
  • 1
    Is your LEVEL a varchar??? 3 > 1. Commented Dec 13, 2017 at 17:53
  • 1
    Which dbms??? It's the most important thing when asking for question. You don't want to get answer, but useless because it is for the wrong dbms. Like the answer below, it will work if you happen to use SQL Server. But it will not work with other dbms. Commented Dec 13, 2017 at 17:55

2 Answers 2

3

Your Level field is a string. Try this in SQL 2012+:

SELECT MAX(TRY_CONVERT(FLOAT, Level)) AS HIGHESTLEVEL, ACCOUNTNAME
FROM TABLE
GROUP BY ACCOUNTNAME

This will return NULL for any ACCOUNTNAMEs that don't have any valid numeric values for a given value of LEVEL.

Sign up to request clarification or add additional context in comments.

8 Comments

Do you know if there is a way to get around the error? it seems that the column may have values that can't be converter to numeric value.
What RDBMS are you using? The method could vary.
I'm using SQL Server
@OzzyBenitez Then add SQL Server tag to your question.
Thank you @GarethLyons, unfortunately it did not work i got this error:
|
1

Here's one way using TOP and DESC:

SELECT TOP 1 *
  FROM TABLE
ORDER BY CAST([Level] as decimal(16,2)) DESC

Another way using MAX and a group by:

SELECT MAX(CAST([Level] as decimal(16,2))) AS [Level]
      ,AccountName
  FROM TABLE
GROUP BY AccountName

Alternatively, you could change the datatype of [Level] to a decimal or float (which it probably should be, instead of varchar) and your original query would work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.