2010-11-13 87 views
4

我有查詢是這樣說:如何選擇連續日期?

SELECT DISTINCT 
     S.date1 AS date1, 
     S.date2 AS date2, 
     S.period AS period 

FROM portfolio.scenario S 

WHERE S.date1 >= '2010-06-01' AND 
     S.date2 <= '2010-07-01' AND 
     S.period = 'WEEK' 

輸出是:

"2010-06-01 00:00:00","2010-06-08 00:00:00",WEEK 
"2010-06-02 00:00:00","2010-06-09 00:00:00",WEEK 
"2010-06-03 00:00:00","2010-06-10 00:00:00",WEEK 
"2010-06-04 00:00:00","2010-06-11 00:00:00",WEEK 
"2010-06-07 00:00:00","2010-06-14 00:00:00",WEEK 
"2010-06-08 00:00:00","2010-06-15 00:00:00",WEEK 
"2010-06-09 00:00:00","2010-06-16 00:00:00",WEEK 
"2010-06-10 00:00:00","2010-06-17 00:00:00",WEEK 
"2010-06-11 00:00:00","2010-06-18 00:00:00",WEEK 
"2010-06-14 00:00:00","2010-06-21 00:00:00",WEEK 
"2010-06-15 00:00:00","2010-06-22 00:00:00",WEEK 
"2010-06-16 00:00:00","2010-06-23 00:00:00",WEEK 
"2010-06-17 00:00:00","2010-06-24 00:00:00",WEEK 
"2010-06-18 00:00:00","2010-06-25 00:00:00",WEEK 
"2010-06-21 00:00:00","2010-06-28 00:00:00",WEEK 
"2010-06-22 00:00:00","2010-06-29 00:00:00",WEEK 
"2010-06-23 00:00:00","2010-06-30 00:00:00",WEEK 
"2010-06-24 00:00:00","2010-07-01 00:00:00",WEEK 

我需要的僅僅是連續的日期與最早的日期1 startest;

"2010-06-01 00:00:00","2010-06-08 00:00:00",WEEK 
    "2010-06-08 00:00:00","2010-06-15 00:00:00",WEEK 
    "2010-06-15 00:00:00","2010-06-22 00:00:00",WEEK 
    "2010-06-22 00:00:00","2010-06-29 00:00:00",WEEK 

欣賞的話題:)

回答

4

這不是最佳的性能,使用功能性條款的任何幫助,但只要S.period保持在一個星期,這將這樣的伎倆。

SELECT DISTINCT 
     S.date1 AS date1, 
     S.date2 AS date2, 
     S.period AS period 

FROM portfolio.scenario S 

WHERE S.date1 >= '2010-06-01' AND 
     S.date2 <= '2010-07-01' AND 
     S.period = 'WEEK' AND 
     DAYOFWEEK(S.date1) = DAYOFWEEK('2010-06-01'); 
+0

這很快。謝謝你,它的工作:) – 3ashmawy 2010-11-13 23:32:10

+0

你有任何想法和安迪,如何一個通用的解決方案(不取決於S.period值)? – 3ashmawy 2010-11-15 12:26:05

0

編輯 對不起,我沒看你足夠接近期望的結果。該JOIN將整理那些沒有結尾並且在同一天開始的日期。

你需要CROSS JOIN表所示:

SELECT DISTINCT 
     S.date1 AS date1, 
     S.date2 AS date2, 
     S.period AS period 

    FROM portfolio.scenario S, 
     portfolio.scenario T 

WHERE S.date1 >= '2010-06-01' AND 
     S.date2 <= '2010-07-01' AND 
     S.period = 'WEEK' AND 
    (T.date2 = S.date1 OR 
     S.date1 = '2010-06-01') 

最後一個條件需要或者包括第一排,因爲它不能被T.date2 = S.date1結合。

你在這裏。

+0

它不起作用,只是繼續運行,然後「失去與服務器的連接」 – 3ashmawy 2010-11-15 12:25:24

+0

根據您提供的關於您的設置的內容無法真正瞭解。您是從腳本語言還是直接在數據庫中執行此操作? – aefxx 2010-11-15 16:28:53