oracle 使用两列之间的范围选择

pb3s4cty  于 2023-05-28  发布在  Oracle
关注(0)|答案(1)|浏览(170)

在我的Oracle表中,我有表3列,其中我对2列使用SELECT并检索数据。列的数据类型为NUMBER。
我想检索值,其中,refyear= 2009 AND refmonth in(11,12)and refyear= 2011 AND refmonth in(1)and refyear= 2010 AND refmonth in(1,2,3,4,5,6,7,8,9,10,11,12)
我试图使用下面的SELECT,我认为它给出了错误的行数。我尝试了以下几种方法

select * from TABLEA where  ( refyear= 2009 AND refmonth in (11,12)) OR ( refyear= 2011 AND refmonth in (1)) OR ( refyear= 2010 AND refmonth in (1,2,3,4,5,6,7,8,9,10,11,12))

我想我们必须使用BETWEEN,不知道如何使用。任何帮助都很感激。

TABLEA
year   month     Variance
2009    11          1
2009    12         2.3
2010    12         98
2010    11         5.4
2010    10         8.5
2010    9          8.1
2010    8          4.1
2010    7          6.3
2010    6          4.1
2010    5           7
2010    4          4
2010    3         0.3
2010    2         1.2
2010    1         5.6
2011    1         7.8
2008    12        7.8
2008    11        7.8
2008    10        7.9
vd8tlhqk

vd8tlhqk1#

不要列出所有的年份和月份;使用范围:

SELECT *
FROM   table_name
WHERE  ( refyear = 2009 AND refmonth >= 11 ) -- Months for start year
OR     ( refyear > 2009 AND refyear < 2011 ) -- All years in between
OR     ( refyear = 2011 AND refmonth <= 1 )  -- Months for end year

或者,将年/月转换为DATE并进行比较:

SELECT *
FROM   table_name
WHERE  TO_DATE(refyear || '-' || refmonth || '-01', 'YYYY-MM-DD')
         BETWEEN DATE '2009-11-01'
             AND DATE '2011-01-01'

或者,如果你确实想列出年份(如果你不想只列出一个连续的范围),那么:

SELECT *
FROM   table_name
WHERE  ( refyear, refmonth ) IN (
         (2009, 11),
         (2009, 12),
         (2010,  1),
         (2010,  2),
         (2010,  3),
         (2010,  4),
         (2010,  5),
         (2010,  6),
         (2010,  7),
         (2010,  8),
         (2010,  9),
         (2010, 10),
         (2010, 11),
         (2010, 12),
         (2011,  1),
       )

相关问题