简体   繁体   English

如何按字母数字值对数据进行排序

[英]How to sort the data in alphanumeric values

I have these values: d1, d45, d79, d33, d100 我有这些值: d1, d45, d79, d33, d100

I want to sort these variables in ascending order from my table. 我想从表中按升序对这些变量进行排序。

What is the query to get the output as: 什么是获取输出的查询:

d1
d33
d45
d79
d100

What you want is called a "natural sort". 您想要的被称为“自然排序”。 For Microsoft SQL Server 2005, see this question . 对于Microsoft SQL Server 2005,请参阅此问题 For other languages, see (for example) this other question . 对于其他语言,请参阅(例如) 另一个问题

Sorry, not SQL answer at all. 抱歉,根本没有SQL答案。 :) For variant with one letter only order by length and alpha. :)对于只有一个字母的变体,仅按长度和字母顺序排序。

If you can guarantee a pattern of /\\w\\d+/ ... 如果您可以保证/ \\ w \\ d + /的模式...

In postgres: 在postgres中:

select foo from bar order by cast(substring(foo from 2) as int)

..and similar will exist for other SQL flavours. ..以及其他SQL风格也将存在。 Expensive mind. 昂贵的头脑。

edit: androids solution looks good too: 编辑:androids解决方案看起来也不错:

..order by char_length(foo),foo

If we can assume that the data values only contain the letter d and a numeric value, then you can also use: 如果我们可以假设数据值仅包含字母d和数字值,那么您还可以使用:

select column from YourTable
order by convert(int, replace(column, 'd', ''))

If it contains any other letters, then this method rapidly becomes unusable: 如果它包含任何其他字母,则此方法将迅速变得不可用:

select column from YourTable
order by convert(int, 
        replace(replace(replace(replace(replace(
            column, 'a', ''),
                'b', ''),
                'c', ''),
                'd', ''), 
                'e', '')
        )

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

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