提取天/小时/分钟

时间:2019-02-05 09:37:26

标签: sql sql-server date

我有下面的代码正在运行,但是如何获取终端分钟以将输出显示为日,时,分?如果无法做到这一点,是否可以在表示第二天的时间上加上+1?

我遇到的问题是,当我们的订单运行时间超过23.59 PM时,由于24小时,系统无法显示正确的格式。

enter image description here 我很沮丧,希望我不要把事情弄糊涂。

SELECT FOLIO_NUMBER, TERMINAL_NAME,
  format((START_LOAD_TIME - ORDER_ENTRY_TIME), 'HH:mm') AS STAGING_MINUTES, 
  format((TERM_END_LOAD_TIME - START_LOAD_TIME), 'HH:mm') AS LOADING_MINUTES,
  format((TERM_END_LOAD_TIME - ORDER_ENTRY_TIME), 'HH:mm') AS TERMINAL_MINUTES 
FROM ORDERS  
JOIN TERMINAL_OWNER ON ORDERS.LOADING_TERMINAL_ID = TERMINAL_OWNER.TERMINAL_ID

3 个答案:

答案 0 :(得分:1)

我认为您正在寻找类似的东西

Declare @theMinutes Varchar(10)
Set @theMinutes = '19:25' 

declare @totMintute int
Select    
  @totMintute = (Cast(
  Cast(left(@theMinutes,charindex(':',@theMinutes)-1) as Int) * 60
  + Cast(substring(@theMinutes,charindex(',',@theMinutes)+4,len(@theMinutes)) as Int)  
as Int ) * 60) / 60

--For 12 hour 1 days
Select @totMintute / 720 as NoDays  -- 720 minutes per day 
       , (@totMintute % 720) / 60 as NoHours -- modulo 720 
       , (@totMintute % 60) as NoMinutes -- modulo 60

--For 24 hour 1 days
Select @totMintute / 1440 as NoDays  -- 1440 minutes per day 
       , (@totMintute % 1440) / 60 as NoHours -- modulo 1440 
       , (@totMintute % 60) as NoMinutes -- modulo 60

输出将如下所示。

enter image description here

您可以如下所示转换此查询数据源表。

Create table #Temp (MinValue Varchar(8))
insert into #Temp Values ('19:25')

Select TotMinute / 720 as NoDays  -- 1440 minutes per day 
       , (TotMinute % 720) / 60 as NoHours -- modulo 1440 
       , (TotMinute % 60) as NoMinutes -- modulo 60
from(
select 
(Cast(
  Cast(left(MinValue,charindex(':',MinValue)-1) as Int) * 60
  + Cast(substring(MinValue,charindex(',',MinValue)+4,len(MinValue)) as Int)
as Int ) * 60) / 60  as TotMinute
from #Temp
)a

您可以找到实时演示here

答案 1 :(得分:1)

DECLARE @INT INT

SET @INT = DATEDIFF(SECOND,GETDATE(),GETDATE()+1)

select 
convert(varchar(10), (@INT/86400)) + ':' + 
convert(varchar(10), ((@INT%86400)/3600)) + ':'+
convert(varchar(10), (((@INT%86400)%3600)/60)) + ':'+
convert(varchar(10), (((@INT%86400)%3600)%60)) as 'DD:HH:MM:SS'

由Nat-MS提供。参见here

答案 2 :(得分:1)

我要说的是,您无需在SQL输出中标识天/小时,而只需数分钟即可得到差异,然后您就可以在应用程序层中使用它了。

this sample code

create table #orders (
    FOLIO_NUMBER int,
    START_LOAD_TIME datetime,
    ORDER_ENTRY_TIME datetime,
    TERM_END_LOAD_TIME datetime
)

insert into #orders (FOLIO_NUMBER,START_LOAD_TIME,ORDER_ENTRY_TIME,TERM_END_LOAD_TIME)
values (1, getdate(),getdate() - 1,getdate() + 1)

select *, 
    datediff(mi, ORDER_ENTRY_TIME, START_LOAD_TIME) AS STAGING_MINUTES,
    datediff(mi, START_LOAD_TIME, TERM_END_LOAD_TIME) AS LOADING_MINUTES,
    datediff(mi, ORDER_ENTRY_TIME, TERM_END_LOAD_TIME) AS TERMINAL_MINUTES
from #orders

drop table #orders

这将输出事件之间的分钟差:

FOLIO_NUMBER    STAGING_MINUTES LOADING_MINUTES TERMINAL_MINUTES
1               1440            1440            2880

然后您可以使用这些值执行一些简单的数学运算,以提取天,小时和分钟。