如何在Sql Query

时间:2018-02-02 05:22:19

标签: sql sql-server database sql-server-2008 sql-server-2012

表格列是:

time         date 
-----        ------------- 

21:02:03     2/1/2018
22:05:13     2/1/2018
20:25:13     2/1/2018

我想只为特定日期添加时间21:02:03 + 22:05:13 + 20:25:13 = 63:32:29 输出为63:32:29

表名是时间表

我需要查询总时间总和。

6 个答案:

答案 0 :(得分:1)

您可以将时间转换为秒并将该值加起来

SELECT DATEADD(ms, SUM(DATEDIFF(ms, 0, [timecolumn])), 0)

或者,只需计算倒数时间(以秒为单位),并将其转换为您的格式

SELECT count_down_sec = SUM(DATEDIFF(SECOND, '0:00:00', [timecolumn])) 

完整查询

SELECT CAST(tottime /60/60 AS nvarchar) 
                +':'+CAST(tottime /60%60 AS nvarchar) 
                +':'+ CAST(tottime % 60 AS nvarchar)    
FROM    (
    SELECT  SUM(DATEDIFF(SECOND, 0, [time])) AS tottime
    FROM    [schedule] 
    WHERE   [date]='2/1/2018'
)   AS T

输出:

count_down_sec
63:32:29

答案 1 :(得分:1)

试试这个,

SELECT  
IFNULL(SEC_TO_TIME( SUM( TIME_TO_SEC( `time1` ) ) ),'00:00:00') AS Time 
FROM schedule ;

答案 2 :(得分:0)

请尝试这样

    select dateadd(second,datediff(second,0,time1),time2) as Time3 from your_table

我认为这会起作用

答案 3 :(得分:0)

将SUM函数应用于要添加时间的列(假设列的数据类型为TIME)。

https://www.techonthenet.com/sql/sum.php

答案 4 :(得分:0)

在MySQL中,您可以使用以下sql,

(?s)([\S, ]*)\n(.*)

以下是详细信息:

SELECT date(timedatecol) date1,
       sec_to_time(SUM(time_to_sec(time(timedatecol)))) timetotal
FROM schedule
GROUP BY date1;

输出以下sql

CREATE TABLE `schedule` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timedatecol` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;

Inserted Data:
'1', '2018-02-02 06:19:05'
'2', '2018-02-02 06:19:06'
'3', '2018-02-02 06:19:07'
'4', '2018-02-03 06:19:08'
'5', '2018-02-03 06:19:08'
'6', '2018-02-04 06:19:08'
'7', '2018-02-04 06:19:09'
'8', '2018-02-02 06:19:09'

答案 5 :(得分:0)

尝试这种方法

DECLARE @T TABLE
(
    MyTime TIME,
    MyDate DATE DEFAULT('2/1/2018')
)

INSERT INTO @T(MyTime)
VALUES('01:02:03'),('01:05:13'),('03:25:59')

;WITH CTE
AS
(
    SELECT
       MyDate,
       NewTime = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)
       FROM @T
),C2
AS
(
    SELECT
       MyDate,
       MyMin = SUM(DATEDIFF(MINUTE, MyDate, NewTime))
       FROM CTE
          GROUP BY MyDate
)
SELECT
    MyDate,
    CAST(MyDate AS DATETIME)+CAST(RTRIM(MyMin/60) + ':' + RIGHT('0' + RTRIM(MyMin%60),2) AS DATETIME)
    FROM C2

我的结果

MyDate     MyTime
---------- -----------------------
2018-02-01 2018-02-01 05:32:00.000