拆分表时的Oracle sql比较

时间:2015-01-30 21:13:31

标签: sql oracle

我有大表TRANSACTION表,我想获得2015年1月和不属于2015年1月的另一列的关键列,以便我比较表中已存在的列。

  • 从期间= 2015年1月的交易中选择关键列
  • 从期间的交易中选择关键列!= 2015年1月

然后比较已存在与否的两列。 我如何为此编写oracle sql?

1 个答案:

答案 0 :(得分:0)

如果这只是检查其他时期的交易是否存在,那么请使用:

select t1.tdate, t1.key_column,
     case 
       when exists (
         select 1 from transactions t2
           where t2.key_column = t1.key_column
             and t2.tdate not between to_date('2015-01-01', 'yyyy-MM-dd') 
                                  and to_date('2015-01-31', 'yyyy-MM-dd') 
         )
      then 'transactions in other months exists'
      else 'transactions in other months not found'
    end notices
  from transactions t1
  where t1.tdate between to_date('2015-01-01', 'yyyy-MM-dd') 
                     and to_date('2015-01-31', 'yyyy-MM-dd')

使用样本数据进行测试:

with transactions as (
  select to_date('2015-01-01') tdate, 17 key_column from dual
  union select to_date('2015-01-11') tdate, 123 key_column from dual
  union select to_date('2015-01-31') tdate, 90 key_column from dual
  union select to_date('2014-06-22') tdate, 17 key_column from dual
  union select to_date('2015-02-01') tdate, 19 key_column from dual
  union select to_date('2015-02-01') tdate, 90 key_column from dual
  )
select t1.tdate, t1.key_column,
     case 
       when exists (
         select 1 from transactions t2
           where t2.key_column = t1.key_column
             and t2.tdate not between to_date('2015-01-01', 'yyyy-MM-dd') 
                                  and to_date('2015-01-31', 'yyyy-MM-dd') 
         )
      then 'transactions in other months exists'
      else 'transactions in other months not found'
    end notices
  from transactions t1
  where t1.tdate between to_date('2015-01-01', 'yyyy-MM-dd') 
                     and to_date('2015-01-31', 'yyyy-MM-dd')

输出:

tdate      key_column    notices
2015-01-01         17    transactions in other months exists
2015-01-11        123    transactions in other months not found
2015-01-31         90    transactions in other months exists

如果您想以更复杂的方式比较交易,请附加一些输入,所需的输出和您的尝试(如果有的话)。