日期:2014-05-16  浏览次数:21111 次

查询如何讲数据按照指定区间进行区分,望高手指教
需求:表A

 AAC001 ALC034
  0001 2011-06-25
  0002 2011-05-25


需要查询的结果是,将ALC034与当前日期进行比如,将相差的月份罗列出来。

假设今日为2011-08-24,期望得到的结果集如下:

 AAC001 ******
  0001 2011-07
  0001 2011-08
  0002 2011-06
  0002 2011-07
  0002 2011-08

------解决方案--------------------
SQL code

[SYS@myorcl] SQL>WITH T1 AS
  2   (SELECT '0001' AAC001, DATE '2011-06-25' ALC034
  3      FROM DUAL
  4    UNION
  5    SELECT '0002' AAC001, DATE '2011-05-25' ALC034 FROM DUAL)
  6  SELECT AAC001, COLUMN_VALUE
  7    FROM T1,
  8         TABLE(CAST(MULTISET
  9                    (SELECT TO_CHAR(ADD_MONTHS(TRUNC(ALC034, 'mm'), LEVEL),
 10                                    'yyyy-mm')
 11                       FROM DUAL
 12                     CONNECT BY LEVEL <=
 13                                MONTHS_BETWEEN(TRUNC(SYSDATE, 'mm'),
 14                                               TRUNC(ALC034, 'MM'))) AS
 15                    SYS.ODCIVARCHAR2LIST));

AAC0 COLUMN_VALUE
---- --------------------
0001 2011-07
0001 2011-08
0002 2011-06
0002 2011-07
0002 2011-08

[SYS@myorcl] SQL>