又有问题了,高手请进!

cnwhm 2003-08-22 10:03:12
现有下面的表:产品表
品名 日产 月产 日期
A 10 100 2003-8-21
B 20 110 2003-8-21
C 15 100 2003-8-21
A 5 2003-8-22
B 10 2003-8-22
C 12 2003-8-22

    公式:今日月产=昨日月产+今日日产
结果:
品名 日产 月产 日期
A 10 100 2003-8-21
B 20 110 2003-8-21
C 15 100 2003-8-21
A 5 105 2003-8-22
B 10 120 2003-8-22
C 12 112 2003-8-22

要计算出今天的月产。用最短的sql语句实现。并实现效率最优。
...全文
32 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
cnwhm 2003-08-22
  • 打赏
  • 举报
回复
下面的这句报错:
update 产品表 set 月产=tem.月产+产品表.日产 from 产品表 tem where datediff(day,tem.日期,产品表.日期)=1 and tem.品名=产品表.品名 and 产品表.日期='2003-8-22'
服务器: 消息 107,级别 16,状态 3,行 1
列前缀 '产品表' 与查询中所用的表名或别名不匹配。
pengdali 2003-08-22
  • 打赏
  • 举报
回复
报什么错?

update 产品表 set 产品表.月产=tem.月产+产品表.日产 from (select * from 产品表 where 日期='2003-8-22') tem where datediff(day,tem.日期,产品表.日期)=1 and tem.品名=产品表.品名

happydreamer 2003-08-22
  • 打赏
  • 举报
回复

update 表
set 月产=日产+isnull ( ( select 月产 from tt where datediff(day,a.日期,日期)=-1 and 品名=a.品名) ,0)
from 表 a
where a.日期='2003-8-22'
happydreamer 2003-08-22
  • 打赏
  • 举报
回复

update 表
set 月产=日产+isnull ( ( select 月产 from tt where datediff(day,a.日期,日期)=-1 and 品名=a.品名) ,0)
from 表 a
where a.日期='2003-8-22'
nboys 2003-08-22
  • 打赏
  • 举报
回复
改为:
update 产品表 set 月产=tem.月产+产品表.日产 from 产品表,(select * from 产品表) tem where datediff(day,tem.日期,产品表.日期)=1 and tem.品名=产品表.品名 and 产品表.日期='2003-8-22'
nboys 2003-08-22
  • 打赏
  • 举报
回复

update a set 月产 = isnull((Select 月产 from 产品表 where 品名 = a.品名 and 日期 = a.日期-1 ) + 日产,0)
from 产品表 a where 日期='2003-8-22'

执行的应该快一点
cnwhm 2003-08-22
  • 打赏
  • 举报
回复
大力的我怎么没试通!

update a set 月产 = isnull((Select 月产 from 产品表 where 品名 = a.品名 and 日期 = a.日期-1 ) + 日产,0)
from 产品表 a where 日期='2003-8-22'

to CrazyFor:
这样结果就上去了。
update 产品表
set 月产=isnull((select top 1 月产 from 产品表 bb where aa.品名=bb.品名 and bb.日期<aa.日期 order by 日期 desc)+aa.日产,0) from 产品表 aa where 日期='2003-8-22'

上面两个哪个更快?
CrazyFor 2003-08-22
  • 打赏
  • 举报
回复
select aa.*,(select top 1 月产 from 表 bb where aa.品名=bb.品名 and bb.日期<aa.日期 order by 日期 desc)+aa.日产 as MonthTotal from 表 aa
pengdali 2003-08-22
  • 打赏
  • 举报
回复
update 产品表 set 月产=tem.月产+产品表.日产 from 产品表 tem where datediff(day,tem.日期,产品表.日期)=1 and tem.品名=产品表.品名 and 产品表.日期='2003-8-22'
cnwhm 2003-08-22
  • 打赏
  • 举报
回复
应该再加上日期。
update a set 月产 = (Select 月产 from yourTable where 品名 = a.品名 and 日期 = a.日期-1 ) + 日产
from yourTable a where 日期='2003-8-22'
txlicenhe 2003-08-22
  • 打赏
  • 举报
回复
update a set 月产 =
(Select 月产 from yourTable where 品名 = a.品名 and 日期 = a.日期-1 ) + 日产
from yourTable a
txlicenhe 2003-08-22
  • 打赏
  • 举报
回复
update a set 月产 =
(Select 月产 from yourTable where 品名 = a.品名 and 日期 = a.日期-1 ) + 日产
from yourTable a
cnwhm 2003-08-22
  • 打赏
  • 举报
回复
同意 nboys() 的观点!
txlicenhe(不做技术高手) 的方法是快!


谢谢楼上的诸位高手!!!
结贴。

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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