假设需求场景如下:
t_user(主表)
Id  name  ServiceExpiryDate(服务终止日期,date类型)
1   lisi  2012/12/12
2   lucy  2011/12/23t_user_assist(次表,UserId是外键)
UerId IsSuperUser
1      1
2      0t_service_plan(次表)UserId ServiceName  buyServcieTime(date类型)
2      ServcieA     2011/12/11
2      ServiceB     2012/09/12
现在用一条sql脚本实现以下需求:
如果user是超级用户(IsSuperUser=1),把主表的ServiceExpiryDate修改为9999/12/31
否则
就遍历t_service_plan这个表来获取用户的最后购买服务计划的buyServcieTime(因为一个用户可以购买多个Service plan,应该order by buyServcieTime desc,然后取第一条记录),获取到buyServcieTime之后,再做以下事情:
如果buyServcieTime<=2012/01/01,则修改购买了此service plan 用户的ServiceExpiryDate为2013/12/31.
如果buyServcieTime>2012/01/01&&buyServcieTime<=2013/03/01,则修改购买了此service plan 用户的ServiceExpiryDate为2014/12/31.
或者设置ServiceExpiryDate为null.请高手指教,不胜感激。
遍历

解决方案 »

  1.   

    为何要先排序然后取第一条?难道max解决不了这个问题?update t_user a
       set serviceexpirydate =
            (select case
                      when b.issuperuser = 1 then
                        to_date('9999/12/31', 'yyyy/mm/dd')
                      else
                       (select case
                                 when max(c.buyservicetime) <= to_date('2012/01/01', 'yyyy/mm/dd') then
                                   to_date('2013/12/31', 'yyyy/mm/dd')
                                 when max(c.buyservicetime) > to_date('2012/01/01', 'yyyy/mm/dd') and
                                      max(c.buyservicetime) <= to_date('2013/01/01', 'yyyy/mm/dd') then
                                   to_date('2014/12/31', 'yyyy/mm/dd')
                               end
                          from t_service_plan c
                         where a.id = c.userid)
                    end
               from t_user_assist b
              where a.id = b.userid);
      

  2.   

    update t_user set ServiceExpiryDate=
      decode(IsSuperUser,1,to_date("9999/12/31","yyyy/mm/dd"),max(buyServcieTime)<=to_date("2012/01/01","yyyy/mm/dd",to_date("2013/12/31","yyyy/mm/dd"),
    max(buyServcieTime)>to_date("2012/01/01","yyyy/mm/dd") and max(buyServcieTime)<=to_date("2013/03/01","yyyy/mm/dd")
    ,
    to_date("2014/12/31","yyyy/mm/dd")
    ,null
    )  from t_user ,t_user_assist ,t_service_plan where   t_user.id = t_user_assist.UerId and t_user_assist.UerId =t_service_plan.UserId      
      

  3.   


    decode里面可以使用表达式了吗?