需要格式化char(4)hhmm到时间或文本在sql中看起来像hh:mm

时间:2015-10-21 23:24:56

标签: sql

在下面的脚本中,如何将列HHMM转换为HH:MM
    把它转换成12小时的时钟?

该列为char(4),格式为0000 - 2359。     只想要时间或带冒号的文本(:),没有日期。

请注意,我不想要日期或秒数。我该怎么做呢?     谢谢你的帮助!

Select    
          th.[store] as 'My Store',
    --->  this column th.hhmm as Time, (I need this to format hh:mm)
          emp.[First Name],
          td.Type as [Total],
          Count(*) as Qty,
          Convert(varchar(50),SUM(Amount1),1) AS Amount

3 个答案:

答案 0 :(得分:0)

您可以使用substr在Oracle中执行此操作。

select substr(th.hhmm,1,2)||':'||substr(th.hhmm,3,2) from t

在SQL Server中,您可以使用substring

select substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2) from t

Fiddle with sample data

编辑:

select 
case when cast(substring(th.hhmm,1,2) as int) < 12 then
          case when cast(substring(th.hhmm,1,2) as int) = 0 then
          '12'+':'+substring(th.hhmm,3,2)+' AM'
          else substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2)+' AM' end 
     when cast(substring(th.hhmm,1,2) as int) > 12 then 
     cast(substring(th.hhmm,1,2)%12 as varchar(2)) +':'+substring(th.hhmm,3,2)+' PM' 
     when cast(substring(th.hhmm,1,2) as int) = 12 then
     substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2)+' PM' 
end

答案 1 :(得分:0)

试试这个。它使用LEFTRIGHT函数

declare @time char(4)='2359'
select left(convert(varchar(100),cast(concat(left(@time,2),':',right(@time,2)) as time),9),5)+
              ' '+
       right(convert(varchar(100),cast(concat(left(@time,2),':',right(@time,2)) as time),9),2)

答案 2 :(得分:0)

SQL Server:

right('00' + cast((cast(substring(th.hhmm, 1, 2) as int) - 1) % 12 + 1 as varchar(2)), 2) +
':' + substring(th.hhmm, 3, 2) +
case when cast(substring(th.hhmm, 1, 2) as int) >= 12 then 'pm' else 'am' end