按字符改变时间字符串?

时间:2013-08-08 19:33:46

标签: sql postgresql postgresql-9.1

我正在查询表格,我正在尝试Order By一个“时间”列,其时间格式为“下午1点到2点”,“早上7点到8点”,“上午11点 - 12点” pm“等等我不允许改变这个专栏,但我想不出一个好的方法来查询它,以便我可以通过ascdesc正确订购。我试着找位置或“上午”。或“p.m.”并使用PostgreSLQ子串方法,但我仍然遇到麻烦。

2 个答案:

答案 0 :(得分:2)

在查询中添加sortby列

select blah
, case when timefield = "earlier than 1am" then 1
when timefield = "1-2 am" then 2
etc
else 20 end sortby
etc
order by sortby

答案 1 :(得分:1)

我认为你可以这样做:

order by to_timestamp(time, 'HH a.m.');

以下是一个例子:

select time, to_timestamp(time, 'HH a.m.')
from (select '1 p.m. - 2 p.m.' as time union all
      select '9 a.m. - 10 a.m.' as time union all
      select '11 a.m. - 12 p.m.' as time
     ) t
order by to_timestamp(time, 'HH a.m.');
相关问题