Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92387178
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: Oracle

2008-04-09 11:17:30

   来源:IT 专家网   

曾经,有个用户提出了以下的一个问题,随即有很多朋友提供了他们的解决方案,我们的专家将这些记录整理出来,供大家参考学习。

  问:要求把表B按照CLM001分组求和计算score的值,然后加到表A中对应CLM001的score的值。如何写更新表A的SQL语句?

  表A:

  CLM001        SCORE

  001                 0

  002                 0

  003                 0

  004                 0

  其中CLM001是主键。

  表B:

  ID CLM001 SCORE

  0      001       12

  1      001       24

  2      002      110

  3      004      220

  4      004       20

      答:

  with r as {

  select CLM001 ,sum(score) as total from b group by CLM001

  }

  update a set score = (select total from r where r.CLM001 =a.CLM001)

  where exists (select 1 from r where r.CLM001 =a.CLM001)

  点评:此方法需要写存储过程,否则在程序中没法用。

  create or replace procedure p_test

  as

  v_clm001 a.clm001%type;

  cursor c_record is

  select distinct clm001 from b;

  begin

  open c_record;

  loop

  fetch c_record into v_clm001;

  exit when c_record%notfound;

  update a set score =(select sum(score) from b where clm001=v_clm001)

  where clm001=v_clm001;

  end loop;

  end;

  点评:这是在PL/SQL中的语句,此问题用PL/SQL解决也不失为一个简单的方法。

update a set a.score = a.score + (select b.score from a a,

  (select CLM001,sum(score) from b group by CLM001) b where a.CLM001 = b.CLM001)

  点评:最佳答案,此类问题用视图解决很方便!

阅读(148) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~