0

Let say I have a user table and the record is like this:

----------------------
| User ID | Username |
----------------------
|US1      | Andy     |
|US2      | Boston   |
|US3      | Charlie  |
|US4      | Donnie   |
|US5      | Elmo     |
|US6      | Frank    |
|US7      | Garry    |
|US8      | Henry    |
|US9      | Ignatius |
|US10     | John     |

What I need is

US10      | John

Then I do:

SELECT MAX (UserId) FROM User;

The result was

US9      | Ignatius 

because its ordered by string literally, so US10 is not the max

What should I do to accomplished that result? Thanks in advance.

4 Answers 4

1

If you have fixed format for data like numbers are at last in string then you can use PATINDEX() function to get number from string like

SELECT TOP 1 * FROM [User]
ORDER BY CAST(SUBSTRING(UserId, PATINDEX('%[0-9]%', UserId), LEN(UserId)) AS INT) DESC;

If you have not fixed format for number in string and you want to sort data based on numbers only then check more details in below link

SQL Server 2008 - order by strings with number numerically

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

2 Comments

user is a reserved word in sql so it should be used by brackets around that [user]
yes, I know, it was just for example, still I have updated my answer.
0

NOTE: keep in mind that user is a reserved word in sql so it should be used by brackets around that [user]

There are many options:

1)

select top 1 Userid,
CAST(SUBSTRING(UserId, PATINDEX('%[0-9]%', UserId), LEN(UserId)) AS INT) as Maxid,
username
from [user] 
Order By Maxid desc

Output:

Userid  Maxid   username
=============================
US10    10      John

2)

SELECT TOP 1 * FROM [User]
ORDER BY CAST(RIGHT(UserId,LEN(UserId)-2) AS INT) DESC

Output

userid  username
=====================
US10    John

Comments

0

Assuming that your column format always have the same quantity of character at the beginning, you can use this query to remove the first 2 characters and convert the remaining to number in order the get the proper behaviour on your max query :

SELECT MAX(CAST(SUBSTRING(`UserId` FROM 3) AS UNSIGNED)) FROM `User` ;

Comments

0

Try this query

SELECT TOP 1 * FROM User ORDER BY CAST(RIGHT(UserId,LEN(UserId)-2) AS INT) DESC

OP

US10 | John

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.