Oracle使用Max on date列,并按“跳过”结果排序

时间:2011-07-22 16:30:50

标签: sql oracle

以下查询“跳过”指定范围内的行。

Select Apples.*, Chiquita.color, Bananas.Time   
from Apples,  
(Select Carrot.name, Apple.type, Banana.color, MAX(Carrot.Time) as CarrotTime  
 From Apples Apple, Bananas Banana, Carrots Carrot  
where  Apple.color = Banana.color  
group by Carrot.name, Apple.type, Banana.color) Chiquita  
where rownum <= 20  
order by CarrotTime DESC;

现在,如果我将rownum修改为40,我会得到散布在日期范围之间的结果。澄清:
rownum = 20返回日期如下:

 1,12-Jun-11  
  ...  
  20, 22-May-11 

rownum = 40会返回如下信息:

  1, 12-Jun-11
  ...
  20, 29-May-11  //Notice that this row 20 does not equal the information from the other row 20
  ...  
  40, 22-May-11

3 个答案:

答案 0 :(得分:6)

where rownum <= 20   
order by CarrotTime DESC; 

Oracle在订单之前处理where子句。因此,您的查询选择它碰巧到达的前20行,然后应用CarrotTime的顺序。这通常通过将订单移动到子查询中来修复,如StevieG建议的那样。但是,当结果加入时,无法保证内部查询的顺序。

尝试另一个内部查询(未经测试):

Select *
from (Select Apples.*, Chiquita.color, Bananas.Time
    from Apples,
    (Select Carrot.name, Apple.type, Banana.color, MAX(Carrot.Time) as CarrotTime
        From Apples Apple, Bananas Banana, Carrots Carrot
        where  Apple.color = Banana.color
        group by Carrot.name, Apple.type, Banana.color) Chiquita
    order by CarrotTime DESC)
where rownum <= 20

答案 1 :(得分:2)

除非

,否则你的比较将不准确
a) You view the complete result set from both Queries or

b) You are sure you have only one record in the result set for a given ID..

对于您的示例,当您有两个记录时可能会有...

20, 22-May-11
20, 29-May-11 

在加入后以及添加rownum&lt; 20,你看到第一行,rownum&lt; 40,你看到第二排。

如果您希望结果集保持一致,则可能必须在获得前20或40行之前对结果进行排序。

像...这样的东西。

select * from (
Select Apples.*, Chiquita.color, Bananas.Time   
from Apples,  
(
  Select Carrot.name, Apple.type, Banana.color, MAX(Carrot.Time) as CarrotTime  
  From Apples Apple, Bananas Banana, Carrots Carrot  
  where  Apple.color = Banana.color  
  group by Carrot.name, Apple.type, Banana.color
  order by MAX(Carrot.Time)
) Chiquita  
order by CarrotTime DESC
)
where rownum < 20 ---or rownum < 40

此外,您的查询似乎有笛卡尔联接,

1)Chiquita内部(3张桌子,只有一张加入)

2)苹果和Chiquita之间

这通常是一个错误,所以你可能想要研究一下。

答案 2 :(得分:1)

我猜它是因为子查询中的行没有排序。试试这个:

Select Apples.*, Chiquita.color, Bananas.Time   
from Apples,  
(
  Select Carrot.name, Apple.type, Banana.color, Carrot.CarrotTime
  From Apples Apple, Bananas Banana, 
       ( 
         select name, MAX(Time) as CarrotTime 
         from Carrots 
         group by name
         order by MAX(Time), name
       ) Carrot
  where  Apple.color = Banana.color  
  group by Carrot.name, Apple.type, Banana.color
  order by Carrot.CarrotTime, Carrot.name)
) Chiquita  
where rownum <= 20  
order by CarrotTime DESC;