日期:2014-05-17  浏览次数:20964 次

oracle的子查询里不让有order by 有什么好的解决办法么,我先说一下我的需求。。。。。
table_task
table_customer

customer 和 task 是 一对多的关系。一个custo对应多个task

我现在想要把 task表 按inserttime desc顺序第一条的taskgoing字段值

更新到customer表里的 lastgoingtask里。


update GR_P_Customer cu set F_LastTaskGoing = 
(select ta.F_TaskGoing from GR_C_Task ta
where rownum = 1 and ta.F_Customer = cu.F_Key 
order by ta.F_InsertTime desc)

运行 “ORA-00907: 缺失右括号”


------解决方案--------------------
这个不难,但也比想像中要复杂。

因为是要根据某一列(时间)找出其最大值对应那一行对应的另一列(顾客)
所以直接用max函数是不行的

先要用开窗的统计函数找出这种对应关系,如



        select  F_Customer,          F_TaskGoing,F_InsertTime,
          row_number() over(partition by F_Customer order by F_InsertTime desc) rn
        from  F_TaskGoing 
        

有了这个对应关系就好办了:
        




 
update  GR_P_Customer cu
set cu.F_LastTaskGoing = (
      select  ta.F_TaskGoing
      from  (
        select  F_Customer,
          F_TaskGoing,F_InsertTime,
          row_number() over(partition by F_Customer order by F_InsertTime desc) rn
        from  F_TaskGoing 
        ) ta
      where ta.F_Customer = cu.F_Key
      and rn = 1
    )