簡體   English   中英

SELECT查詢在SQL Server中按子字符串排序

[英]SELECT query ordering by substring in Sql Server

我在SQL Server表中的一列具有以下行:

MyColumn:

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

它是包含優先級字符串的文本列。

有沒有一種方法可以使選擇返回此列的順序如下:

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

等等..

謝謝

試試這個解決方案:

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提琴演示

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)
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]的順序提供所有不同的值(月,周等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM