CREATE TABLE "DBA"."TIME_SPENT_DATA" (
"id" BIGINT NOT NULL,
"manual_number" INTEGER NULL,
"user_id" INTEGER NULL,
"session_id" VARCHAR(100) NULL,
"total_time_on_site" VARCHAR(100) NULL,
"date_t" DATE NULL,
PRIMARY KEY ( "id" ASC )
) IN "system";
id,manual_number,user_id,session_id,total_time_on_site,date_t
3,38001,1357,'123','**3h27m42s**','2014-10-02'
4,38001,1357,'123','**2h20m42s**','2014-10-02'
我想这样做:
select manual_number,user_id,session_id, sum(total_time_on_site)
FROM "DBA"."TIME_SPENT_DATA" group by manual_number,user_id,session_id
我知道我不能这样做,因为total_time_on_site是一个varchar。但是我怎样才能做到这一点? 我想添加这些值(如果我有25小时 - 我需要显示1d 1h)
我可以这样做吗?谢谢
答案 0 :(得分:0)
即使您在服务器外部进行转换可能会更好,但我无法抵制摆弄您的数据,如果您想在数据库中进行转换,则应该灵活使用子字符串,charindex和强制转换。工作。不是100%它没有错误,但它确实适用于您相当有限的测试数据。
SELECT
manual_number, user_id, session_id,
CAST(DATEADD(second,SUM(
CAST(SUBSTRING(total_time_on_site, PATINDEX('%[0-60]%', total_time_on_site), CHARINDEX('h',total_time_on_site)-CHARINDEX('*',total_time_on_site,2)-1) AS INT)*60*60+
CAST(SUBSTRING(total_time_on_site, CHARINDEX('h',total_time_on_site,0)+1, CHARINDEX('m',total_time_on_site)-CHARINDEX('h',total_time_on_site,0)-1) AS INT)*60+
CAST(SUBSTRING(total_time_on_site, CHARINDEX('m',total_time_on_site,0)+1, CHARINDEX('s',total_time_on_site)-CHARINDEX('m',total_time_on_site,0)-1) AS INT)
),0)
AS TIME) AS sum_of_total_time_on_site_as_time
FROM TIME_SPENT_DATA
GROUP BY manual_number, user_id, session_id
输出:
manual_number user_id session_id sum_of_total_time_on_site_as_time
------------- ----------- ---------- ---------------------------------
38001 1357 123 05:48:24.0000000