紧急求救:一个极其复杂的SQL算法问题!

leeyoong 2002-02-05 08:56:42
假设有一个表如下:
商品编号 进货数量
0001 10
0001 50
0001 5
0002 20
0003 40
0003 10
0003 10

现在如何用一个SQL构造一个表如下:
商品编号 进货数量 实际总进货
0001 10 10
0001 50 60
0001 5 65
0002 20 20
0003 40 40
0003 10 50
0003 10 60

注意:同一种商品可能存在多次进货,它们以进货时间为序。
拜托诸位大哥了,如找到最佳算法,定会高分相送。
...全文
150 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
karma 2002-02-05
  • 打赏
  • 举报
回复
打赌不解决问题,请说出在这种情形下子查询效率比cursor高的理由来
jasmine 2002-02-05
  • 打赏
  • 举报
回复
我打赌 子查询效率比cursor高,就算是forward的也一样
karma 2002-02-05
  • 打赏
  • 举报
回复
the reason I said it is inefficient is that there are repeated computations involved,

for example, look at these 3 rows
0001 10
0001 50
0001 5

the first select == > 10

the second select ==> 10 +50 = 60

the third select ==> 10 + 50 + 5 = 65
^^^^^^^
the 10+50 step is repeated and not necessary. Will the DBMS optimize away the repeated computations? I doubt




rwq_ 2002-02-05
  • 打赏
  • 举报
回复
如果数据量不大的话,上面几位的是可以了,不然还是用过程好!这样只要扫描一次表就OK了!
progame 2002-02-05
  • 打赏
  • 举报
回复
再加点想法

一、程序后端处理
二、写到临时表再自连接Update

如果说子查询效率不好的话,我想不到效率更好的方法了
karma 2002-02-05
  • 打赏
  • 举报
回复
I think the sub-query method is not efficient
bluepower2008 2002-02-05
  • 打赏
  • 举报
回复
题目说得那么吓人,进来一看也不是那么夸张。
用个子查询就可以搞定了。不过既然是以进货时间为序,就该还有个进货时间字段,先给你加上。
sql语句:
select a.code,a.cnt,(select sum(cnt) from table1 b where b.code = a.code and b.time <= a.time) as total
from table1 a
order by a.code,a.time

--code:商品编号;cnt:进货数量;total:实际总进货;time:进货时间
net_steven 2002-02-05
  • 打赏
  • 举报
回复
select a.*,b.进货数量 as 实际总进货 from yourtable a left join
(select 商品编号, sum(进货数量) as 进货数量 from yourtable group by 商品编号) b
on a.商品编号=b.商品编号
order by a.商品编号


anglely168 2002-02-05
  • 打赏
  • 举报
回复
用cursor怎么写?说啊
xpliuchuming 2002-02-05
  • 打赏
  • 举报
回复
用游标(cursor)是最容易的
40Star 2002-02-05
  • 打赏
  • 举报
回复
你这是按什么排序?进货时间吗
karma 2002-02-05
  • 打赏
  • 举报
回复
use cursor

11,848

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 非技术版
社区管理员
  • 非技术版社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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