2014-10-03 67 views
0
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' 

我想這樣做列:做一個總和 - 組通過在Sybase由代表一段

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小時 - 我需要顯示1天1小時)

我可以這樣做嗎?謝謝

+0

我的$ 0.02:把它關閉到一些代碼,通過一個正則表達式運行它,解析出你的號碼,漏斗垃圾到日誌文件,然後以可用格式將其重新放回數據庫(例如,以整數形式存儲的總秒數)。然後總結一下。 – 2014-10-03 10:21:32

+0

是的,這就是我要做的:)謝謝 – user3796867 2014-10-03 10:46:15

回答

0

即使你在服務器之外進行轉換可能會更好,我無法抗拒你的數據擺弄,如果你確實想在數據庫中做到這一點,一些靈活的使用substring,charindex和casts應該管用。不是100%,它沒有錯誤,但它確實適用於您的相當有限的測試數據。

Sample SQL Fiddle

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