需要根据日期和序列号降序来订购ID
ID是一些串联字符串值的组合 BM-6至8位数字代码-日期(DDMMYY)-序列号(01-99)
Create table #tempcheck (id varchar(50))
Insert into #tempcheck values('BM72220901021904')
Insert into #tempcheck values('BM72220901021906')
Insert into #tempcheck values('BM72220931011901')
Insert into #tempcheck values('BM72220931011903')
Select * from #tempcheck order by id desc
id
BM72220901021906
BM72220901021904
BM72220931011903
BM72220931011901
答案 0 :(得分:1)
尝试一下:
SELECT
*
from #tmpcheck
order by
CONVERT(DATE, SUBSTRING(id, 9, 6)) AS date desc,
CONVERT(int, RIGHT(id,2)) seq desc
问题在于日期之前的部分可以是可变长度
SELECT
*
from #tmpcheck
order by
CONVERT(DATE, SUBSTRING(RIGHT(id, 8), 1, 6)) AS date desc,
CONVERT(int, RIGHT(id,2)) seq desc
答案 1 :(得分:1)
您可以使用以下解决方案:
SELECT CONVERT(DATE, SUBSTRING(id, LEN(id) - 5, 2) + '/' + SUBSTRING(id, LEN(id) - 7, 2) + '/' + SUBSTRING(id, LEN(id) - 3, 2), 1) AS datevalue, RIGHT(id, 2) AS seq
FROM #tempcheck
ORDER BY CONVERT(DATE, SUBSTRING(id, LEN(id) - 5, 2) + '/' + SUBSTRING(id, LEN(id) - 7, 2) + '/' + SUBSTRING(id, LEN(id) - 3, 2), 1) DESC, RIGHT(id, 2) DESC
答案 2 :(得分:0)
此解决方案应该可以做到。它仅使用字符串操作(不进行数据类型转换),并且应该相当快。
SELECT *
FROM #tempcheck
ORDER BY Left(Right(id, 4), 2) + Left(Right(id, 6), 2)
+ Left(Right(id, 8), 2) + Right(id, 2) DESC
它从字符串的后端开始计算字符,因此日期之前的可变长度(6-8)代码无关紧要。