获取从Sql Server中的某个字母开始按字母顺序排序的记录

时间:2009-04-02 09:25:35

标签: sql sql-server regex sql-order-by

在SQLSERVER / MSSQL中,问题出在这里:

SELECT * from [Translation Color] order by [Language Code] 

我想要从'I'字母开始按字母顺序排序记录。

结果示例:

'Ioren' 'Iumen' '酸' 'Arfen' 'Coldry'

我不想使用union或更多的sql语句..只是尝试用特殊子句的命令来捕获它。

我试过了:

ORDER BY <field> REGEXP '^I' DESC

但它不起作用。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

这应该这样做:

ORDER BY CASE WHEN SUBSTRING([Translation Color],1,1) = 'l' 
     THEN 1 ELSE 0 END DESC

编辑:

完全回答订购完全从i开始,然后循环回到h是:

ORDER BY CASE WHEN ASCII(UPPER(SUBSTRING([Translation Color],1,1))) < 73 
         THEN ASCII(UPPER(SUBSTRING([Translation Color],1,1))) + 26
         ELSE ASCII(UPPER(SUBSTRING([Translation Color],1,1))) END ASC,       
         [Translation Color] ASC

请注意,这会影响大型桌子的效果。

答案 1 :(得分:2)

或者这是好事:

select [Translation Color], 
  case when [Translation Color] < 'l' then 1
                     else 0 
                     end as Priority
from t1 
order by Priority, [Translation Color]

这将按字母顺序从'l'开始

修改 这个解决方案似乎对我有用:

create table t1 ( c1 varchar(20) collate SQL_Latin1_General_Cp437_CI_AS)

然后我填充了一些测试数据然后运行:

select c1 
from t1 
order by case when c1 >= 'l' then 0 else 1 end, c1

答案 2 :(得分:1)

SELECT *
FROM [Translation Color]
ORDER BY
    CASE WHEN [Language Code] LIKE '[I-Zi-z]%' THEN 0 ELSE 1 END,
    [Language Code]