SQL Server 2014 - 查找日期之间的活动时段

时间:2015-04-02 04:55:27

标签: sql sql-server-2014 sqldatetime

我有一个名为Device的表,其中模式更改时已记录设备状态

CREATE TABLE MSTR.DEVICE_STATUS_HISTORY
(device_id int, MODE varchar(5) ,CHANGED_TIME datetime);

insert into MSTR.DEVICE_STATUS_HISTORY 
(DEVICE_ID,MODE,CHANGED_TIME)
values (17,'AUTO','2015-03-21 19:30:16.440'),
(17,'MANUAL','2015-03-21 22:20:45.880'),
(17,'AUTO','2015-03-24 11:58:18.990'),
(33,'MANUAL','2015-03-22 17:57:26.670'),
(33,'AUTO','2015-03-24 18:05:59.483 '),
(33,'MANUAL','2015-03-24 19:26:16.210'),
(33,'AUTO','2015-03-25 15:41:14.663 ');

在参数传递期间查找设备自动和手动的小时,分​​钟和秒的要求

例如我想获得从22-03-2015 08:00:0023-03-2015 16:45:35的自动/手动时间段...任何人都可以帮忙写一个查询。

我期待的结果是

Device Status  Hours minutes Seconds
-------------------------------------------------------------------    
17 --> Auto     5  Hours 10 Minutes  2 seconds
17--> Manual    2  Hours 11 Minutes 10 Seconds
33--> Auto      8  Hours 10 Minutes  2 seconds
33--> Manual   12  Hours 11 Minutes 10 Seconds

(小时,分钟和秒只是一个例子与

不匹配

1 个答案:

答案 0 :(得分:0)

使用DATEPART

SELECT  DEVICE_ID
        ,MODE
        ,CONVERT(VARCHAR(2), DATEPART(HOUR, CHANGED_TIME)) + ' Hours' AS Hours
        ,CONVERT(VARCHAR(2), DATEPART(MINUTE, CHANGED_TIME)) + ' Minutes' AS Minutes 
        ,CONVERT(VARCHAR(2), DATEPART(SECOND, CHANGED_TIME)) + ' Seconds' AS Seconds 
FROM MSTR.DEVICE_STATUS_HISTORY
WHERE CHANGED_TIME <= '2015-03-22 08:00:00'
AND CHANGED_TIME >= '2015-03-21 16:45:35'