Re: [SQL ] 請問如何計算重複日期區間的總實際天數

看板Database作者 (可愛小孩子)時間11年前 (2014/09/19 09:33), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
假設 (id,StartDate,EndDate) 是「唯一」: select id,sum(day) day from ( select id,StartDate,EndDate,min(day) day from ( select t2.id,t2.StartDate,t2.EndDate, case when t1.StartDate = t2.StartDate and t1.EndDate = t2.EndDate then t2.day -- (t1 = t2 表示自己本身) when t2.StartDate >= t1.StartDate and t2.EndDate <= t1.EndDate then 0 -- (t2 被 t1 整個包住了) when t2.StartDate >= t1.StartDate and t2.StartDate <= t1.EndDate then t2.day - DATEDIFF(dd,t2.StartDate,t1.EndDate) - 1 -- (部分重疊) else t2.day -- (完全沒重疊) end day from @t t1 inner join @t t2 on t1.id = t2.id where (t2.StartDate > t1.StartDate ) or -- 加上條件後,重疊狀況剩 (t1.StartDate = t2.StartDate and t1.EndDate <= t2.EndDate) ) t group by t.id,t.StartDate,t.EndDate ) t group by t.id ※ 引述《Mutex (Mutex)》之銘言: : 資料庫名稱:SQL : 資料庫版本:2008 : 內容/問題描述:希望計算每個人在區間內的實際天數有幾天 : 但會遇到日期重複的問題 不知道該如何處理 : ID StartDate EndDate day : A 20140101 20140115 15 : A 20140114 20140117 4 : B 20140215 20140220 6 : B 20140220 20140225 6 : C 20140301 20140305 5 : C 20140320 20140321 2 : 希望得到的結果是 : A 17 : B 11 : C 7 : 希望高手能協助幫忙解決了 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.221.80.36 ※ 文章網址: http://www.ptt.cc/bbs/Database/M.1411090409.A.F68.html
文章代碼(AID): #1K6uVfze (Database)
討論串 (同標題文章)
文章代碼(AID): #1K6uVfze (Database)