比较Oracle中同一表中的行

时间:2015-03-02 17:23:59

标签: sql oracle compare

我试图找到在同一个表中的行之间进行比较的最佳方法。 我写了一个自我加入查询,并能够拿出费率不同的那些。现在我需要了解费率是增加还是减少。如果费率增加,这是一个问题。如果它减少了,那就没有问题了。

我的数据看起来像这样

ID       DATE           RATE
1010     02/02/2014      7.4
1010     03/02/2014      7.4
1010     04/02/2014      4.9
2010     02/02/2014      4.9
2010     03/02/2014      7.4
2010     04/02/2014      7.4

所以在我的表中,我应该能够将ID 1010编码为0(无问题),将2010编码为1(问题),因为速率从feb上升到apr。

4 个答案:

答案 0 :(得分:3)

您可以使用select..case

来实现此目的
select case when a.rate > b.rate then 'issue' else 'no issue' end
from yourTable a
join yourTable b using(id)
where a.date > b.date

请参阅documentation for CASE expressions

答案 1 :(得分:1)

select distinct ID from MyData latest
inner join MyData earlier on latest.id = earlier.id
where earlier.date < latest.date and earlier.rate < latest.rate
除非你真的需要选择那些没有问题的方法,否则

会成为获取它们的一种方法吗?

答案 2 :(得分:1)

听起来像LAG()

with sample_data as (select 1010 id, to_date('02/02/2014', 'mm/dd/yyyy') dt, 7.4 rate from dual union all
                     select 1010 id, to_date('03/02/2014', 'mm/dd/yyyy') dt, 7.4 rate from dual union all
                     select 1010 id, to_date('04/02/2014', 'mm/dd/yyyy') dt, 4.9 rate from dual union all
                     select 2010 id, to_date('02/02/2014', 'mm/dd/yyyy') dt, 4.9 rate from dual union all
                     select 2010 id, to_date('03/02/2014', 'mm/dd/yyyy') dt, 7.4 rate from dual union all
                     select 2010 id, to_date('04/02/2014', 'mm/dd/yyyy') dt, 7.4 rate from dual)
select id,
       dt,
       rate,
       case when rate > lag(rate, 1, rate) over (partition by id order by dt) then 1 else 0 end issue
from   sample_data;

        ID DT               RATE      ISSUE
---------- ---------- ---------- ----------
      1010 02/02/2014        7.4          0
      1010 03/02/2014        7.4          0
      1010 04/02/2014        4.9          0
      2010 02/02/2014        4.9          0
      2010 03/02/2014        7.4          1
      2010 04/02/2014        7.4          0

您可能希望围绕该查询抛出外部查询,以仅显示具有issue = 1的行,或者可能是聚合查询以检索至少有一行具有issue = 1的ID,具体取决于您的实际要求。希望以上内容足以让您了解如何获得所需资源。

答案 3 :(得分:0)

选择a。&amp ;,当a.rate&gt;时的情况b.rate然后问题&#39;别的&#39;没问题&#39;结束 从表a 在a.ID = b.ID上连接表b 其中a.date&gt; b.date;

相关问题