简体   繁体   English

MS SQL Server中的订购属性-包括单位

[英]Ordering properties in MS SQL Server - including flats

I have been given a CAG and i'm trying to sort the address by Postcode and Building Number. 我已经获得了CAG认证,我正在尝试按邮政编码和门牌号对地址进行排序。 The problem i face is that Building Number is not actually integer, it's a nvarchar- because of flat properties. 我面临的问题是建筑物号实际上不是整数,而是nvarchar-,因为它具有平坦的属性。

You can see that 79B appears after 143: 您可以看到143之后出现79B:

131
133A
133B
135
137
139
141
143
79B <--
87 
89 
91 

I have found a similar question: sql-for-ordering-by-number-1-2-3-4-etc-instead-of-1-10-11-12 我发现了一个类似的问题: sql-for-ordering-by-number-1-2-3-4-etc-instead-of-1-10-11-12

and tried this 并尝试了这个

SQL += "ORDER BY BUILDNO * 1 ASC ";

but predictably i get a conversion error 但可以预见,我会遇到转换错误

Conversion failed when converting the nvarchar value '133A' to data type int.

Is it possible to order this type of nvarchar in SQL? 是否可以在SQL中订购这种类型的nvarchar?

thanks 谢谢

UPDATE UPDATE

I know have this working, thanks @paYa 我知道有这个工作,谢谢@paYa

SELECT * FROM [" + tblname + "] 
WHERE POSTCODE LIKE + @postcode + '%' 
ORDER BY CAST(LEFT([BUILDNO], CASE WHEN PATINDEX(N'%[^0-9]%', [BUILDNO]) < 1 THEN LEN([BUILDNO]) ELSE PATINDEX(N'%[^0-9]%', [BUILDNO]) - 1 END) AS INT), 
RIGHT([BUILDNO], LEN([BUILDNO]) - PATINDEX(N'%[^0-9]%', [BUILDNO]) + 1)

returns the correct order: 返回正确的顺序:

79B
87 
89 
91 
133B
135
137
139
141
143

in mssql server 在mssql服务器中

order by cast(left([ColName], case when patindex(N'%[^0-9]%', [ColName]) < 1 then len([ColName]) else patindex(N'%[^0-9]%', [ColName]) - 1 end) as int),
right([ColName], len([ColName]) - patindex(N'%[^0-9]%', [ColName]) + 1);

You can use lpad with blank 您可以将lpad与空白一起使用

in mysql 在MySQL中

 ORDER BY lpad(your_column,  16 - length(your_column ), ' ')

in sqlserver 在sqlserver中

  ORDER BY right(replicate(' ',16 - length(your_column )) + YourFieldValue)

Parse Building Number, extract leading integer and all the rest. 解析建筑物编号,提取前导整数,然后提取其余所有整数。 MS SQL: MS SQL:

select nbr
from ( values('79'),('100'),('79B') ) t(nbr)
cross apply (select pos = patindex('%[^0-9]%',nbr+'X')-1 ) x
order by cast(left(nbr, pos) as int)
    , substring (nbr, pos+1, 8000)

Here's a solution with patindex that basically strips the beginning numbers from the varchar . 这是一个使用patindex的解决方案,该解决方案基本上从varchar剥离起始数字。

select *
from yourtable 
order by left(id, patindex('%[a-z]%', id + 'A') - 1)

Similar solutions can be applied to other databases as well. 类似的解决方案也可以应用于其他数据库。

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

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