如何以特定格式汇总周期时间

时间:2013-05-20 10:57:35

标签: sql sql-server datetime sql-server-2012

如果我有这样的结果集:

Work_hour(hh:mm)
10:24
12:59
06:28

where Work_hour is of type varchar

如何以相同的格式汇总这些小时和分钟?

2 个答案:

答案 0 :(得分:3)

SELECT CAST(FLOOR(TMP1.MINS/60) AS VARCHAR) + ':' + CAST((TMP1.MINS % 60) AS VARCHAR) FROM (
    SELECT SUM (CAST(LEFT(time_column, 2) AS INT) * 60 + CAST(RIGHT(time_column, 2) AS INT)) as MINS FROM table1
) AS TMP1

time_column 是表格中的列, table1 是表格的名称。例如:

create table table1 (
    time_column varchar(10)
);
insert into table1 (time_column) values ('12:20'), ('10:40'), ('15:50');

结果: 38:50

答案 1 :(得分:2)

试试这个 -

<强>查询:

DECLARE @temp TABLE
(
      work_hour CHAR(5)
)

INSERT INTO @temp (work_hour)
VALUES 
    ('10:24'),
    ('12:59'),
    ('06:28')

;WITH cte AS
(
    SELECT mn = SUM(DATEDIFF(MINUTE, '19000101', CAST('19000101 ' + work_hour AS DATETIME)))
    FROM @temp
)
SELECT CAST(FLOOR(mn / 60) AS VARCHAR(5)) + ':' + CAST(mn % 60 AS VARCHAR(2))
FROM cte

<强>输出:

hm
--------
29:51

更新2:

DECLARE @temp TABLE
(
      transtime_out DATETIME
    , transtime_in DATETIME
)

INSERT INTO @temp (transtime_out, transtime_in)
VALUES 
    ('2013-05-19 16:40:53.000', '2013-05-19 08:58:07.000'), 
    ('2013-05-19 16:40:53.000', '2013-05-19 08:58:07.000')

SELECT diff = LEFT(CONVERT(VARCHAR(10), CAST(SUM(CAST(a.transtime_out - a.transtime_in AS FLOAT)) AS DATETIME), 108), 5)
FROM @temp a