0

如果我有这样的结果集:

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

where Work_hour is of type varchar

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

4

2 回答 2

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

于 2013-05-20T11:06:59.780 回答
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
于 2013-05-20T11:03:23.847 回答