将2个日期/时间字段连接并计时

时间:2017-09-13 13:07:27

标签: sql sql-server tsql

我试图教自己一些SQL并且无法找到下面的最佳方法

SELECT [BasicStartDateTime]
  ,[BasicFinishTime]
,cast (BasicStartDateTime as varchar(120)) + '-' + CAST(BasicFinishTime as varchar(7))as TimeBand 
FROM [DOCDPT].[main].[Tbl_WorkOrder]
where BasicStartDateTime >'2017-01-01'

这些是我的结果列

BasicStartDateTime

2017-01-03 12:00:00.000

BasicFinishTime

20:00:00.000

TimeBand

Jan  3 2017 12:00PM-8:00PM

理想情况下,我希望最后一栏(时间段)说12:00-20:00

我想要的第一个是12:00pm-8:00Pm然后我会担心24小时后的位时间

我一直试图在连接的第一阶段使用转换,但语法似乎永远不会有效。

3 个答案:

答案 0 :(得分:1)

如果是2012 +

应该注意Format()有一些很棒的功能,但它不是一个表演者。

示例

Declare @YourTable Table ([BasicStartDateTime] datetime,[BasicFinishTime] datetime)
Insert Into @YourTable Values 
 ('2017-01-03 12:00:00.000','2017-01-03 20:00:00.000')

Select * 
      ,TimeBand = format(BasicStartDateTime,'HH:mm-')+format(BasicFinishTime,'HH:mm')
 From @YourTable

<强>返回

BasicStartDateTime        BasicFinishTime           TimeBand
2017-01-03 12:00:00.000   2017-01-03 20:00:00.000   12:00-20:00

答案 1 :(得分:0)

试试这个:

LTRIM(RIGHT(CONVERT(VARCHAR(20), BasicStartDateTime, 100), 7)) + '-' +
LTRIM(RIGHT(CONVERT(VARCHAR(20), cast(BasicFinishTime AS datetime), 100), 7))

答案 2 :(得分:0)

使用convert()个样式,并在转换为basicfinishtime之前将datetime转换为varchar

select 
    basicstartdatetime
  , basicfinishtime
  , timeband = convert(varchar(20), basicstartdatetime, 100)
    +'-'+ltrim(right(convert(varchar(20), convert(datetime,basicfinishtime),100),7))
from tbl_workorder

rextester演示:http://rextester.com/YDMCD58620

返回:

+---------------------+-----------------+----------------------------+
| basicstartdatetime  | basicfinishtime |          timeband          |
+---------------------+-----------------+----------------------------+
| 2017-01-03 12:00:00 | 20:00:00        | Jan  3 2017 12:00PM-8:00PM |
+---------------------+-----------------+----------------------------+