在sql server中进行查询,以对同时包含数字和字母的数据进行排序

在sql server中进行查询,以对同时包含数字和字母的数据进行排序,sql,sql-server,Sql,Sql Server,我的一个表的值如下 Year 1 Year 9 Year 8 Year 4 Kindy [can be any word without numbers] Pre-School [can be any word without numbers] Year 8 Year 22 Year 15.... Kindy Pre-School Year 1 Year 4 Year 8 Year 9 Year 15 Year 22 我怎样才能先按字母顺序,然后按数字升序对它们进行排序呢 Year 1 Y

我的一个表的值如下

Year 1
Year 9
Year 8
Year 4
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 8
Year 22
Year 15....
Kindy 
Pre-School
Year 1
Year 4
Year 8
Year 9
Year 15
Year 22
我怎样才能先按字母顺序,然后按数字升序对它们进行排序呢

Year 1
Year 9
Year 8
Year 4
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 8
Year 22
Year 15....
Kindy 
Pre-School
Year 1
Year 4
Year 8
Year 9
Year 15
Year 22
我试过下列方法

SELECT  YearLevel FROM Student 
ORDER BY 
CASE WHEN YearLevel NOT LIKE '%[0-9]%' THEN 0
ELSE CAST(RIGHT(YearLevel, LEN(YearLevel) - 5) AS int)
END
但问题是我只需要不同的记录

select
        astring
from table1
order by 
        case when left(astring,5) = 'Year ' then 2
           else 1 end
      , case when left(astring,5) = 'Year ' then right(replace(astring,'Year ','00000000'),3)
           else astring end
      , astring

请参见

如果带数字的列始终采用年[digits]格式,您可以尝试此方法

SELECT YearLevel FROM student
GROUP BY YearLevel 
ORDER BY 
    (CASE 
        WHEN YearLevel LIKE 'Year%'
        THEN 'Year' + CONVERT(varchar,LEN(YearLevel)) + YearLevel
        ELSE YearLevel
    END)
虽然这可能有效,但我建议添加一个带有排序顺序的整数列。

请尝试:

SELECT 
    *
FROM
    YourTable
ORDER BY 
    CONVERT(INT, STUFF(Col, 1, PATINDEX('%[0-9]%', Col)-1, '')), 
    LEFT(Col, PATINDEX('%[0-9]%', Col+'1')-2)
这可能是有用的

;WITH cte_Student (YearLevel) as
(SELECT 'Kindy ' UNION ALL
SELECT 'Year 9' UNION ALL
SELECT 'Year 4' UNION ALL
SELECT 'Pre-School' UNION ALL
SELECT 'Year 1' UNION ALL
SELECT 'Year 15' UNION ALL
SELECT 'Year 8' UNION ALL
SELECT 'Year 22')
SELECT YearLevel
FROM cte_Student
ORDER BY
         CASE
         WHEN LEFT(YearLevel, 5) = 'Year ' THEN CAST(SUBSTRING(YearLevel, 5, LEN(YearLevel)) AS INT)
         ELSE 0
         END;

是否存在排序或获取唯一记录的问题?首先要找到想要的独特记录。你有没有尝试过选择不同的请注意,选择不同的作品在整个行我已经标记了这个答案,因为。。。它带来了不同的价值:-