【问题标题】:Using select with cast to do time calculations使用 select with cast 进行时间计算
【发布时间】:2019-09-25 14:11:53
【问题描述】:

我正在选择不同的日期和时间字段,并希望在几分之一小时内计算它们之间的差异。我正在使用 datediff 来获得以分钟为单位的差异,但是当我除以 60 时,我没有得到分数。

尝试转换为十进制和实数

select 
      ,[Call_Date]
      ,[Call_Time]
      ,convert(DATETIME, convert(char(8), call_date, 112)+ ' ' + convert(char(8), Call_time, 108)) as Call_DT
      ,[Roll_Time_Date]
      ,[Roll_Time_Time]
      ,convert(DATETIME, convert(char(8), Roll_time_date, 112)+ ' ' + convert(char(8), Roll_time_time, 108)) as Roll_DT
      ,cast(datediff(mi, (convert(DATETIME, convert(char(8), call_date, 112)+ ' ' + convert(char(8), Call_time, 108))),
                      (convert(DATETIME, convert(char(8), Roll_time_date, 112)+ ' ' + convert(char(8), Roll_time_time, 108))))/60 as decimal)
       As Downtime 
FROM [MFSQL_DTFM].[dbo].[MFWorkOrder] where Customer='Joe'

样本数据:

Call_Date   Call_Time   Call_DT    Roll_Time_Date          Roll_Time_Time Roll_DT   Downtime
2019-04-01  15:39:00    2019-04-01 15:39:00.000 2019-04-02  13:01:00     2019-04-02 13:01:00.000    21
2019-04-01  15:54:00    2019-04-01 15:54:00.000 2019-04-01  17:10:00     2019-04-01 17:10:00.000    1
2019-04-01  16:15:00    2019-04-01 16:15:00.000 2019-04-01  21:30:00     2019-04-01 21:30:00.000    5

【问题讨论】:

  • 您能添加您的预期输出吗?我不明白您想从查询中得到什么。
  • 对于这个 sn-p,我希望 (roll_date&roll_time) - (call_date&call_time) 表示为小时的小数部分。例如,如果通话日期/时间是 2019 年 1 月 1 日 00:01:00,滚动日期/时间是 2019 年 1 月 2 日 00:01:30,我希望结果是 24.5

标签: sql date select time


【解决方案1】:

将 60 AS 十进制更改为 60.0

这将使值默认为十进制,而不必从 int 转换。

【讨论】:

    【解决方案2】:

    也许这样的事情会起作用?

    with mainTimes as (
      select
        Call_Date
       ,Call_Time
       ,convert(DATETIME, convert(char(8), call_date, 112)+ ' ' + convert(char(8), Call_time, 108)) as Call_DT
       ,Roll_Time_Date
       ,Roll_Time_Time
       ,convert(DATETIME, convert(char(8), Roll_time_date, 112)+ ' ' + convert(char(8), Roll_time_time, 108)) as Roll_DT
      from [MFSQL_DTFM].[dbo].[MFWorkOrder]
      where Customer='Joe'
    )
    select *,
      datediff(mi,Call_DT,RollDT)/60.0 as Downtime
    from mainTimes
    

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多