简体   繁体   中英

how to sort alphanumeric data in sql..?

i have items table which is having Size as follows:

1sq.mm.
1.5sq.mm.
0.5sq.mm.
2.5sq.mm.
0.75sq.mm.
4sq.mm.
20mm
25mm
20mtr
75mm x 50mm
100mm x 50mm
100mm x 100mm
75mm x 75mm

i wanted to display it has

0.5sq.mm.
0.75sq.mm.
1.5sq.mm.
2.5sq.mm.
4sq.mm.
20mm
20mtr
25mm
75mm x 50mm
75mm x 75mm
100mm x 50mm
100mm x 100mm

i tried the following sql query but am getting error

'Conversion failed when converting the varchar value '1 sq.mm.' to data type int.'

SQL query:

  select * from Items 
  order by CAST(SUBSTRING(Sizes, PATINDEX('%[0-9]%', Sizes), LEN(Sizes)) AS INT)

Use REPLACE in the ORDER BY

SELECT Sizes
FROM Items
ORDER BY CAST(REPLACE(Sizes,'sq.mm.','') as NUMERIC(9,2))

OUTPUT:

Sizes
0.5sq.mm.
0.75sq.mm.
1sq.mm.
1.5sq.mm.
2.5sq.mm.
4sq.mm.

SQL Fiddle: http://sqlfiddle.com/#!3/ad91f/3/0

CREATE FUNCTION udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO

SELECT dbo.udf_GetNumeric('sada322sds232132132');

drop function udf_GetNumeric;



Result
322232132132



CAST(dbo.udf_GetNumeric(Sizes) AS INT)

Try this:

SELECT Sizes       
FROM Items
ORDER BY CAST(LEFT(Sizes, PATINDEX('%[a-z]%', Sizes)-1) as numeric(9, 2))

that's assuming your data will always be number followed by at least one alphabetic char.

sql fiddle (thanks to matt!)

Just a suggestion - not an answer:

I would reconsider to design the table differently - if possible. At the moment, you are sorting a column with two different types of information: length (mm) and area (sq.mm) which makes little sense.

Maybe you would rather have a data structure like this:

CREATE TABLE MyTable(
  length decimal(5,2),
  width decimal(5,2),
  area decimal(10,2),
  unit varchar(10)
)

Needless to say that with this design it would be very simple to sort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM