选择间隔为6个月的记录

时间:2014-04-18 08:15:43

标签: sql oracle date intervals date-arithmetic

我想用oracle sql语句选择6个月时间间隔的记录。

实施例

01/06/2011  AMOUNT
01/12/2011  AMOUNT 
01/06/2012 AMOUNT
01/12/2012 AMOUNT

等等

如何使用oracle sql执行此操作?

3 个答案:

答案 0 :(得分:2)

select ADD_MONTHS(trunc(sysdate), (rownum - 1) * 6) some_date
  from dual
connect by level <= 5;

SOME_DATE
-----------
18.04.2014
18.10.2014
18.04.2015
18.10.2015
18.04.2016

答案 1 :(得分:0)

WITH     got_r_num     AS
(
     SELECT     t.*     -- OR WHATEVER YOU WANT
     ,     DENSE_RANK () OVER ( PARTITION BY TRUNC (created_date, 'MONTH')
                         ORDER BY       TRUNC (created_date)     -- DESC
                       )     AS r_num
     FROM     test_table
     WHERE     MOD ( MONTHS_BETWEEN ( TRUNC (SYSDATE)
                         , TRUNC (created_date)
                         )
              , 6
              ) = 0
)
SELECT     *     -- or list all columns except r_num
FROM     got_r_num
WHERE     r_num     = 1
;

请查看here

答案 2 :(得分:0)

如果您需要在AMOUNT字段中汇总所有6个月的记录: 您可以使用sum函数进行子查询,并使用CONNECT BY LEVEL

进行查询
SELECT x AS l_date, 
(
SELECT sum(your_data)
FROM your_table
WHERE table_date >= x
 AND table_date   < add_months(x,6)
)AMOUNT
FROM(
     SELECT add_months(to_date('01/06/2011','dd/mm/yyyy'),(LEVEL-1)*6) x
     FROM dual
     CONNECT BY LEVEL <= 4
);