在Sql Server中通过子字符串进行SELECT查询排序

时间:2012-07-10 07:44:25

标签: sql sql-server sql-server-2008

我在SQL Server表中有一列包含以下行:

MyColumn:

1 Month
2 Week
10 Minutes
1 week
12 hours
1 days
2 month
2 day
5 minutes
1 hours

这是一个包含优先级字符串的文本列。

有没有办法让select这个列按照以下顺序返回:

10 Minutes
5 minutes
1 hours
10 Hours
1 day
2 days
1 week
2 weeks
1 month
2 months

等。

谢谢

3 个答案:

答案 0 :(得分:1)

试试这个解决方案:

SELECT mycolumn
FROM tbl
ORDER BY
    SUBSTRING(mycolumn, PATINDEX('%[^0-9]%', mycolumn)+1, 999),
    CAST(LEFT(mycolumn, PATINDEX('%[^0-9]%', mycolumn)-1) AS INT)

SQL-Fiddle Demo

答案 1 :(得分:0)

order by case when patindex('%Month', MyColumn) > 0
              then 0
              when patindex('%week', MyColumn) > 0
              then 1
              when patindex('%days', MyColumn) > 0
              then 2
              when patindex('%Minutes', MyColumn) > 0
              then 3
         end, 
         cast(substring(MyColumn, 1, CHARINDEX(' ', MyColumn)) as int)

答案 2 :(得分:0)

select T4.cnt +' '+T4.name from (         
select substring(name, 1, CHARINDEX(' ', name)) cnt,substring(name,CHARINDEX(' ', name)+1,LEN(name)) name from test4) T4      
left outer join (
select 1 as id,'Month' As name union all
select 2 as id,'Week' As name union all
select 3 as id,'Day' As name union all
select 4 as id,'Minutes' As name )T6
on t4.name=t6.name
order by t6.id,t4.cnt

你必须在左表中按照你想要的顺序给出所有不同的值(月,周等......)“union all”