2014-02-25 68 views
0

我想选择已租用汽车的最新客户,它的ID在参数中输入。这个程序有什么问题?

这是我的代码:

create or replace procedure Q9(idcar int) as 
    cursor c is 
     select client 
     from rent r 
     where r.car=idcar 
     and begindate = (select max(begindate) 
          from rent r2 
          where r.client=r2.client); 
    clientn varchar(50); 

    begin 

    for k in c loop 

     select clientname 
     into clientn 
     from client c 
     where c.idcl=k.client; 

     dbms_output.put_line(clientn);  
    end loop; 

    end; 
+1

告诉我们,它有什么问题?你得到一个错误,或不是预期的结果? –

+0

@PatrickHofman,它打印出租车的所有客户姓名,而我想打印出最新的一个。 –

+1

这意味着您的光标中的查询将返回所有客户端,而不是您获取进行最新预订的客户端的目标。您需要修复您的光标查询 – Incognito

回答

3

这是您的查询:

select client 
from rent r 
where r.car=idcar and 
     begindate = (select max(begindate) from rent r2 where r.client=r2.client); 

这得到,因为相关子查询的最近的为每一个客户记录。

下得到对begindate最大价值的所有出租:

select r.client 
from rent r 
where r.car = idcar and 
     r.begindate = (select max(r2.begindate) from rent r2); 

以上可能会返回什么。您可能需要:

select r.client 
from rent r 
where r.car = idcar and 
     r.begindate = (select max(r2.begindate) from rent r2 where r2.car = r.car); 

这会返回在出租汽车的最近日期租用汽车的客户。

编辑:

上面应该工作。如果你只想要一个值,你可以这样做:

select client 
from (select r.client 
     from rent r 
     where r.car = idcar 
     order by begindate desc 
    ) t 
where rownum = 1; 
+0

为什么我错过了首先阅读WHERE子句本身! :) –

+0

@Gordon Linoff,同样的结果,它打印所有的客户端。 –

+0

@ user3194430。 。所有客户是否有可能在最近的日期租用该类型的汽车? –