SQL语句以计算两天之间的时间

时间:2019-03-29 16:35:02

标签: mysql sql

我有一个MySql数据库表,要在其中获取两个时间戳之间的所有记录。每次状态更改时,我都会获得一个新的时间戳和一个新的Status

类似这样:Status_List

 Status            Time_Start        Time_End
    2               14:00:12          14:13:33
    5               14:13:33          15:33:41
    9               15:33:41          16:02:11

当我搜索时:

select * from Status_List where Time_Start between (15:00:00 and 16:00:00)
Output: 9  15:33:41  16:02:11

但是我需要:

Output: 5 15:00:00  15:33:41
        9 15:33:41  16:00:00

这可能吗?

3 个答案:

答案 0 :(得分:1)

您可以使用如下查询:

SELECT 
    Status
    ,CAST(GREATEST('15:00:00',Time_Start) AS TIME(0)) as Time_Start
    , Time_end
FROM Status_List
WHERE 
    Time_Start BETWEEN '15:00:00' AND '16:00:00'
OR  
    Time_start < '15:00:00' AND Time_End > '15:00:00';

样本

MariaDB [test]> SELECT 
    -> Status
    -> ,CAST(GREATEST('15:00:00',Time_Start) AS TIME(0)) as Time_Start
    -> , Time_end
    -> FROM Status_List
    -> WHERE 
    -> Time_Start BETWEEN '15:00:00' AND '16:00:00'
    -> OR  
    -> Time_start < '15:00:00' AND Time_End > '15:00:00';
+--------+------------+----------+
| Status | Time_Start | Time_end |
+--------+------------+----------+
|      5 | 15:00:00   | 15:33:41 |
|      9 | 15:33:41   | 16:02:11 |
+--------+------------+----------+
2 rows in set (0.001 sec)

MariaDB [test]> 

答案 1 :(得分:1)

使用UNION ALL:

set @start = '15:00:00', @end = '16:00:00';

select status, @start start, time_end end from status_list
where time_start = 
  (select max(time_start) from status_list where time_start <= @start)
union all
select status, time_start, time_end from status_list
where time_start > @start and time_end < @end 
union all
select status, time_start, @end from status_list
where time_end = 
  (select min(time_end) from status_list where time_end >= @end)

请参见demo
结果:

| status | start    | end      |
| ------ | -------- | -------- |
| 5      | 15:00:00 | 15:33:41 |
| 9      | 15:33:41 | 16:00:00 |

答案 2 :(得分:0)

如果我做对了,那么您希望获得行的起始位置在范围内或结尾处的行。要截断超出范围的值,可以使用CASE表达式。

SELECT status,
       CASE
         WHEN time_start < '15:00:00' THEN
           '15:00:00'
         ELSE
           time_start
       END time_start,
       CASE
         WHEN time_end > '16:00:00' THEN
           '16:00:00'
         ELSE
           time_end
       END time_end
       FROM status_list
       WHERE time_start >= '15:00:00'
             AND time_start < '16:00:00'
              OR time_end >= '15:00:00'
                 AND time_end < '16:00:00';

db<>fiddle