我有示例数据
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
答案 0 :(得分:2)
按字段的LENGTH排序,然后按长度相等的值排序:
SELECT myfield from mytable order by
LENGTH(myfield) DESC,
myfield DESC
答案 1 :(得分:1)
如果数据总是在前面有SMMP,您可以使用以下内容:
ORDER BY LPAD(REPLACE(myfield,'SMMP',''),15,'0') desc;
这种方法的逻辑是忽略前面的4个字符,只对后面的数字进行排序。
答案 2 :(得分:1)
按照我之前的评论,排序如下: -
SELECT myfield
FROM mytable
ORDER BY SUBSTRING(myfield, 1, 4) DESC, cast(SUBSTRING(myfield, 5) AS unsigned) DESC
请注意,这仅适用于您的字段是固定格式,其中包含4个字符后跟数字
答案 3 :(得分:1)
这很好用。 下面的代码适用于SQL Server 2008 R2:
SELECT
myfield
FROM mytable
ORDER BY
LEN(myfield) DESC
,myfield DESC