一个可能比较简单的更新语句的问题:分组求和,然后根据求和结果更新

jjdelphi 2003-09-06 04:48:33
数据表如下:
No Month Score1 Score2 IsOK
1 1 10 12
1 2 11 10
1 3 9 9
2 1 8 7
2 2 9 20

要先按No分别对Score1、Score2汇总,把每个月的值加起来。
然后把汇总结果相除,即sum(Score1)/sum(Score2),
再把结果大于0.5(即sum(Score1)/sum(Score2)>0.5)的记录的IsOK字段赋值为True。
...全文
65 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2003-09-06
  • 打赏
  • 举报
回复
效率差不多.

加0.0是为了将整数转换为实型,因为整形相除的结果仍然为整数,根本得不到小数结果,所以要转换一下,你用convert进行数据类型转换也行.
txlicenhe 2003-09-06
  • 打赏
  • 举报
回复
请试一下如下语句就知道为什么要加+0.0了
Select 5/10
select 5.0/10
pengdali 2003-09-06
  • 打赏
  • 举报
回复
update 表 set IsOk='True' where [no] in (select [NO] from 表 group by [No] having sum(Score1)/(sum(Score2)+0.0)>0.5)



如果是整数为什么要 +0.0?
应为要转换成浮点数。
pengdali 2003-09-06
  • 打赏
  • 举报
回复
update 表 set IsOk='True' where [no] in (select [NO] from 表 group by [No] having sum(Score1+0.0)/sum(Score2)>0.5)
jjdelphi 2003-09-06
  • 打赏
  • 举报
回复
zjcxc(邹建) :
1、使用分组和不分组两种方法哪种效率高?
2、如果是整数为什么要 +0.0?
zjcxc 2003-09-06
  • 打赏
  • 举报
回复
如果IsOk是字符型的话,用:
update 表 set IsOk='True'
from 表 a
where (select sum(Score1+0.0)/sum(Score2) from 表 where No=a.No)>0.5

或:
update 表 set IsOk='True'
from 表 a inner join (
select NO,Score=sum(Score1+0.0)/sum(Score2) from 表 grou by No
) b on a.No=b.No
where b.Score>0.5
zjcxc 2003-09-06
  • 打赏
  • 举报
回复
如果你的表中score1和score2是整型的话,用下面的更新语句:

update 表 set IsOk=1
from 表 a
where (select sum(Score1+0.0)/sum(Score2) from 表 where No=a.No)>0.5

或:
update 表 set IsOk=1
from 表 a inner join (
select NO,Score=sum(Score1+0.0)/sum(Score2) from 表 grou by No
) b on a.No=b.No
where b.Score>0.5

zjcxc 2003-09-06
  • 打赏
  • 举报
回复
或:
update 表 set IsOk=1
from 表 a inner join (
select NO,Score=sum(Score1)/sum(Score2) from 表 grou by No
) b on a.No=b.No
where b.Score>0.5
sdhdy 2003-09-06
  • 打赏
  • 举报
回复
update tablename set isok=case when a.score1/a.score2>0.5 then 'true' else 'false' end
from (select no,sum(score1)*1.0 score1,sum(score2)*1.0 score2 from tablenanme group by no) a where a.no=tablename.no
zjcxc 2003-09-06
  • 打赏
  • 举报
回复
update 表 set IsOk=1
from 表 a
where (select sum(Score1)/sum(Score2) from 表 where No=a.No)>0.5

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧