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.

Willy Lazuardi
  • 1,806
  • 4
  • 26
  • 41

4 Answers4

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

Community
  • 1
  • 1
Upendra Chaudhari
  • 6,473
  • 5
  • 25
  • 42
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` ;
MQuirion
  • 323
  • 2
  • 5
0

Try this query

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

OP

US10 | John

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
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
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105