如何选择连续日期?

时间:2010-11-13 23:21:46

标签: mysql

我有这样的查询:

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;

    "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

感谢有关该主题的任何帮助:)

2 个答案:

答案 0 :(得分: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');

答案 1 :(得分:0)

修改 对不起,我没有仔细看你想要的结果。此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' )

最后一个条件需要OR包含第一行,因为它不能由T.date2 = S.date1加入。

你走了。