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

跪求一下一条sql脚本
假设需求场景如下:
t_user(主表)
Id  name  ServiceExpiryDate(服务终止日期,date类型)
1   lisi  2012/12/12
2   lucy  2011/12/23

t_user_assist(次表,UserId是外键)
UerId IsSuperUser
1      1
2      0

t_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.

请高手指教,不胜感激。
遍历

------解决方案--------------------
为何要先排序然后取第一条?难道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
                   &n