在SQL Server中对字符串时间使用ORDER BY

时间:2016-05-31 05:57:58

标签: sql sql-server sql-server-2012

所有我都有下表,我需要排序,具体取决于它开始的时间。

示例数据:

4:30pm-10:00pm
5:00am-4:00pm
10:30am-4:00pm
2:00pm-10:45pm
5:00am-3:00pm|3:30pm-10:00pm
NA
7:30am-3:30pm
10:00am-3:30pm
7:31am-1:01pm
2:00pm-10:00pm

所以在上面的示例字符串中,我需要它按顺序排序:

5:00am-3:00pm
5:00am-4:00pm
7:30am-3:30pm
7:31am-1:01pm
10:00am-3:30pm
10:30am-4:00pm
2:00pm-10:00pm
2:00pm-10:45pm
3:30pm-10:00pm
4:30pm-10:00pm

目前,我在运行此查询时收到以下信息:

SELECT [id]
      ,[mon]
FROM [DBc83].[dbo].[tmpTable]
ORDER BY mon DESC

输出是:

id  mon
9   7:31am-1:01pm
7   7:30am-3:30pm
2   5:00am-4:00pm
5   5:00am-3:00pm
1   4:30pm-10:00pm
6   3:30pm-10:00pm
4   2:00pm-10:45pm
10  2:00pm-10:00pm
3   10:30am-4:00pm
8   10:00am-3:30pm

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    [id],[mon]
FROM 
    [DBc83].[dbo].[tmpTable]
ORDER BY 
    convert(time, substring(mon,0,charindex('-',mon))), 
    convert(time, substring(mon,charindex('-',mon)+1,len(mon)))

答案 1 :(得分:1)

请尝试以下内容,

SELECT [id],
       [mon]
FROM   [DBc83].[dbo].[tmpTable]
ORDER BY
       CAST(LEFT(mon, CHARINDEX('-', mon) -1) AS TIME),
       CAST(RIGHT(mon,LEN(mon)-(CHARINDEX('-',mon))) AS TIME)

Cast是ANSI,ANSI-SQL在数据库平台上更具可移植性 所以我在这里使用了Cast,它会按照您的预期输出工作!

LiveDemo

<强> Updated Answer

SELECT [id],
       [mon]
FROM   [DBc83].[dbo].[tmpTable]
ORDER BY
       CAST(LEFT(NULLIF(mon,'NA'), CHARINDEX('-', NULLIF(mon,'NA')) -1) AS TIME),
       CAST(RIGHT(NULLIF(mon,'NA'),LEN(NULLIF(mon,'NA'))-(CHARINDEX('-',NULLIF(mon,'NA')))) AS TIME)

New Updated Answer

这可能是解决方案。

;WITH cte AS(
SELECT [id],
       [mon]
FROM   [DBc83].[dbo].[tmpTable]
WHERE  [mon] NOT LIKE '%|%' 
UNION ALL
SELECT [id],
       LEFT(
           LEFT(mon, LEN(mon) -CHARINDEX('|', mon)),
           LEN(LEFT(mon, LEN(mon) -CHARINDEX('|', mon))) -1
       ) [mon]
FROM   [DBc83].[dbo].[tmpTable]
WHERE  [mon] LIKE '%|%' 
UNION ALL
SELECT [id],
       RIGHT(mon, LEN(mon) -CHARINDEX('|', mon)) [mon]
FROM   [DBc83].[dbo].[tmpTable]
WHERE  [mon] LIKE '%|%' )

SELECT id,[mon] FROM cte 
order by CAST(LEFT(NULLIF(mon,'NA'), CHARINDEX('-', NULLIF(mon,'NA')) -1) AS TIME),
       CAST(RIGHT(NULLIF(mon,'NA'),LEN(NULLIF(mon,'NA'))-(CHARINDEX('-',NULLIF(mon,'NA')))) AS TIME)