在sql server中查询以对具有数字和字母的数据进行排序

时间:2014-07-19 06:50:24

标签: 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

我试过以下......

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

但问题是我只需要不同的记录..

4 个答案:

答案 0 :(得分:0)

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

请参阅this sqlfiddle

答案 1 :(得分:0)

如果带有数字的列始终具有Year [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)

http://sqlfiddle.com/#!3/1919c/3

虽然这可行,但我建议添加一个带排序顺序的整数列。

答案 2 :(得分:0)

请尝试:

SELECT 
    *
FROM
    YourTable
ORDER BY 
    CONVERT(INT, STUFF(Col, 1, PATINDEX('%[0-9]%', Col)-1, '')), 
    LEFT(Col, PATINDEX('%[0-9]%', Col+'1')-2)

SQL Fiddle Demo

答案 3 :(得分:0)

这可能很有用

;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;