简体   繁体   English

如何在SQL中排序字母数字数据..?

[英]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 我尝试了以下SQL查询,但出现错误

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

SQL query: SQL查询:

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

Use REPLACE in the ORDER BY ORDER BY使用REPLACE

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 SQL小提琴: 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!) sql小提琴(感谢马特!)

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. 目前,您正在对一列包含两种不同类型信息的列进行排序:长度(mm)和面积(sq.mm),这毫无意义。

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. 不用说,采用这种设计,将非常容易分类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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