全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:1056
推到 Plurk!
推到 Facebook!

日期為同一天, 但加總時部份要加總到別天

答題得分者是:Fishman
hagar
版主


發表:143
回覆:4056
積分:4445
註冊:2002-04-14

發送簡訊給我
#1 引用回覆 回覆 發表時間:2005-08-31 11:52:36 IP:210.242.xxx.xxx 未訂閱
Table 的 schema 如下: id log_date start_time total_time -- ------------------ ---------- ---------- 1 2005/8/26 00:00:00 0 10 1 2005/8/26 00:00:00 30 15 1 2005/8/26 00:00:00 100 0 1 2005/8/26 00:00:00 130 0 ... 1 2005/8/26 00:00:00 700 0 1 2005/8/26 00:00:00 730 10 ... 1 2005/8/26 00:00:00 2300 10 1 2005/8/26 00:00:00 2330 0 1 2005/8/26 00:00:00 0 10 1 2005/8/26 00:00:00 30 15 1 2005/8/26 00:00:00 100 0 1 2005/8/26 00:00:00 130 0 ... 1 2005/8/27 00:00:00 700 0 1 2005/8/27 00:00:00 730 10 ... 1 2005/8/27 00:00:00 2300 10 1 2005/8/27 00:00:00 2330 0 其中 log_date 為 varchar 型態, 表示記錄日期 start_time 為 int 型態, 值為 30 表示凌晨 12 點半, 值為 100 表示凌晨 1 點, 依此類推 小弟現在的需求如下: 將 2005/8/26 日的 730 ~ 2330 與 2005/8/27 日的 0 ~ 700 的 total_time 欄位加總 將 2005/8/27 日的 730 ~ 2330 與 2005/8/28 日的 0 ~ 700 的 total_time 欄位加總 依此類推. 請問一下大家, 上述需求有辦法以一個 SQL 解決嗎? 小弟用如下的 SQL, 可是結果不對! Select a.id, a.log_date, sum(a.total_time b.total_time) From table1 a, (select id, log_date, total_time from table1 where start_time <= 700) b where cast(cast(a.log_date as datetime) as int) 1 = cast(cast(b.log_date as datetime) as int) and a.start_time >= 730 Group By a.id, a.log_date -- 金也空 銀也空 死後何曾在手中. 妻也空 子也空 黃泉路上不相逢. 田也空 地也空 換過多少主人翁. 名也空 利也空 轉眼荒郊土一封. hagar.
Fishman
尊榮會員


發表:120
回覆:1949
積分:2163
註冊:2006-10-28

發送簡訊給我
#2 引用回覆 回覆 發表時間:2005-08-31 13:06:51 IP:210.65.xxx.xxx 未訂閱
Hi hagar 大大,
試試這樣下(for SQL Server):    select  id,
        case when start_time > 700 then cast(log_date as datetime) else cast(log_date as datetime) - 1 end as log_date, 
        sum(total_time) as total_time
from    table2
group by  
        id,
        case when start_time > 700 then cast(log_date as datetime) else cast(log_date as datetime) - 1 end    翻成白話就是:
select  id,
        log_date,
        sum(total_time) as total_time
from   (select  id,
                cast(log_date as datetime) as log_date,
                total_time
        from    table2
        where   start_time > 700
        union all
        select  id,
                cast(log_date as datetime) - 1 as log_date,
                total_time
        from    table2
        where   start_time <= 700) a
group by
        id,
        log_date
發表人 -
------
Fishman
hagar
版主


發表:143
回覆:4056
積分:4445
註冊:2002-04-14

發送簡訊給我
#3 引用回覆 回覆 發表時間:2005-08-31 13:35:12 IP:210.242.xxx.xxx 未訂閱
只有給分與口頭讚美 無法完全表達小弟對 Fishman 大大的景仰! 謝謝 Fishman 大大! SQL 還真是博大精深啊! -- 金也空 銀也空 死後何曾在手中. 妻也空 子也空 黃泉路上不相逢. 田也空 地也空 換過多少主人翁. 名也空 利也空 轉眼荒郊土一封. hagar.
系統時間:2024-06-01 23:55:46
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!