1

我有示例数据

SMMP022011304196
SMMP022011304199    
SMMP022011304197    
SMMP022011304193
SMMP022011304195    
SMMP022011304198    
SMMP022011304192    
SMMP0220113041910   
SMMP022011304191
SMMP022011304194

如果我使用SELECT myfield from mytable order by myfield DESC 我会得到这样的结果

SMMP022011304199    
SMMP022011304198    
SMMP022011304197    
SMMP022011304196    
SMMP022011304195    
SMMP022011304194    
SMMP022011304193    
SMMP022011304192    
SMMP0220113041910   
SMMP022011304191

请帮助做出这样的结果:

SMMP0220113041910   
SMMP022011304199    
SMMP022011304198    
SMMP022011304197    
SMMP022011304196    
SMMP022011304195    
SMMP022011304194    
SMMP022011304193    
SMMP022011304192    
SMMP022011304191
4

4 回答 4

2

只需按字段的长度排序,然后对长度相等的值进行排序:

SELECT myfield from mytable order by 
LENGTH(myfield) DESC,
myfield DESC

SQLFiddle 演示

于 2013-04-19T08:35:26.733 回答
1

这工作正常。下面的代码适用于 SQL Server 2008 R2:

SELECT 
   myfield  
FROM mytable 
ORDER BY 
    LEN(myfield) DESC 
    ,myfield DESC
于 2013-04-19T08:51:13.627 回答
1

如果数据总是在前面有 SMMP,你可以使用下面的:

ORDER BY LPAD(REPLACE(myfield,'SMMP',''),15,'0') desc;

该方法的逻辑是忽略前面的 4 个字符,只对后面的数字进行排序。

于 2013-04-19T08:35:20.467 回答
1

按照我之前的评论,排序如下: -

SELECT myfield
FROM mytable
ORDER BY SUBSTRING(myfield, 1, 4) DESC, cast(SUBSTRING(myfield, 5) AS unsigned) DESC

请注意,这仅适用于您的字段为固定格式且 4 个字符后跟数字的情况

于 2013-04-19T08:46:24.577 回答