pl sql,如何为每个组的每个时间间隔只保留一行

时间:2013-11-26 22:49:59

标签: sql group-by row oracle-sqldeveloper intervals

我正在使用Oracle SQL Developer和下表:

GROUP DATE  
1     2013-01-01  
1     2013-01-02  
1     2013-06-01  
1     2013-06-30  
1     2013-08-01  
2     2013-01-01  
2     2013-01-02  
2     2013-01-03  
2     2013-12-31  

我想在每组中每隔50天只保持一行,
所以结果表是:

GROUP DATE  
1     2013-01-01  
1     2013-06-01  
1     2013-08-01  
2     2013-01-01  
2     2013-12-31  

所以我想保留每组的每一行,如果有,我想选择
50天后DATE中的下一个DATE,依此类推,直到该组的最后一行。

感谢

1 个答案:

答案 0 :(得分:0)

作为向正确方向迈出的第一步,你可以使用它。它适用于您的样本数据,但仅检查每个组的第一个日期,然后检查所有日期大于或等于该日期+ 50天。不知道如何每50天只检查一个日期。

WITH
    t AS
    (
        SELECT
            1 g,
            '2013-01-01' d
        FROM
            dual
        UNION ALL
        SELECT
            1 g,
            '2013-01-02' d
        FROM
            dual
        UNION ALL
        SELECT
            1 g,
            '2013-06-01' d
        FROM
            dual
        UNION ALL
        SELECT
            1 g,
            '2013-01-30' d
        FROM
            dual
        UNION ALL
        SELECT
            1 g,
            '2013-08-01' d
        FROM
            dual
        UNION ALL
        SELECT
            2 g,
            '2013-01-01' d
        FROM
            dual
        UNION ALL
        SELECT
            2 g,
            '2013-01-02' d
        FROM
            dual
        UNION ALL
        SELECT
            2 g,
            '2013-01-03' d
        FROM
            dual
        UNION ALL
        SELECT
            2 g,
            '2013-12-31' d
        FROM
            dual
    )
SELECT
    g,
    to_char(d_date, 'yyyy-mm-dd') d
FROM
    (
        SELECT
            g,
            MIN(to_date(d, 'yyyy-mm-dd')) d_date
        FROM
            t
        GROUP BY
            g
    )
UNION ALL
SELECT
    t.g,
    t.d
FROM
    t,
    (
        SELECT
            g,
            MIN(to_date(d, 'yyyy-mm-dd')) d_date
        FROM
            t
        GROUP BY
            g
    )
    t1
WHERE
    to_date(t.d, 'yyyy-mm-dd') >= t1.d_date+50
  and t.g = t1.g
    Order by g, d
  ;

输出:

"G"                           "D"                           
-----------------------------------------
"1"                           "2013-01-01"                  
"1"                           "2013-06-01"                  
"1"                           "2013-08-01"                  
"2"                           "2013-01-01"                  
"2"                           "2013-12-31"