Reputation: 33
I am trying to get the MAX of a field in SQL. The field takes numeric and non numeric characters. If the field has the values A, B, C the result should be C. But when the field has for example A, B, C, 1, 2 the result should be 2. Can someone please assist me on how I can achieve this??
Thank You
Upvotes: 2
Views: 75
Reputation: 12309
Try this : May solve your problem at some level
DECLARE @T TABLE(data VARCHAR(2))
INSERT INTO @T VALUES('A'),('B'),('C'),('1'),('2')
SELECT TOP(1) data
FROM @T
ORDER BY CASE WHEN ISNUMERIC(data)=1
THEN 'Z'+data
ELSE data
END desc
Upvotes: 1
Reputation: 13700
Do conditional ordering
select n from
(
select '1' as n union all
select '2' as n union all
select 'A' as n union all
select 'B' as n union all
select 'C' as n
) t
order by case when isnumeric(n)=1 then 1 else 2 end,n desc
select n from
(
select 'A' as n union all
select 'B' as n union all
select 'C' as n
) t
order by case when isnumeric(n)=1 then 1 else 2 end,n desc
Upvotes: 0
Reputation: 28751
This works
SELECT TOP 1 IDValue
FROM
(
SELECT 'A' as IDValue, ISNUMERIC('A') tag
UNION
SELECT 'C', ISNUMERIC('C')
UNION
SELECT 'B', ISNUMERIC('B')
UNION
SELECT '1',ISNUMERIC('1')
UNION
SELECT '2',ISNUMERIC('2')
)tmp
ORDER BY tag DESC,IDValue DESC
2
ISNUMERIC() returns 1 if expression is number else 0 . You can use it in ORDER BY
to fetch max value.
Upvotes: 1
Reputation: 93
here's the syntax for finding max value with SQL
SELECT MAX(column_name) FROM table_name;
you could refer to http://www.w3schools.com/sql/sql_func_max.asp for further reading and code testing
Upvotes: 0