两张表
tb1:
商品号 商品总数
1 420
2 330
.... ....
tb2:
店号 商品号 定货数 实际分到货数
1 1 50 45
2 2 40 40
3 3 55 33--------------------------------------------------
将tb1中一种商品总数分到各个店中,店有优先级别,优先级高的先分,用什么函数还是什么哪?想了一天没想出来,大家帮忙,如果麻烦简单告我方法也可,谢了!
tb1:
商品号 商品总数
1 420
2 330
.... ....
tb2:
店号 商品号 定货数 实际分到货数
1 1 50 45
2 2 40 40
3 3 55 33--------------------------------------------------
将tb1中一种商品总数分到各个店中,店有优先级别,优先级高的先分,用什么函数还是什么哪?想了一天没想出来,大家帮忙,如果麻烦简单告我方法也可,谢了!
解决方案 »
- SQL2008表中数据的单元格是只读属性,不能更改数据,请教怎么设置属性为非只读
- SQL6.5怎么做自动备份?
- 如何检查一个库里的所有表的索引?
- 请教一个sql语句
- access语句到SQLSERVER的转换!!TRANSFORM的!急!!!!!!!!!!!!!
- 弱弱的问:判断一个数据库存在,然后将它删除的SQL语句是什么????
- win7 x64安装SQL SERVER 2005出错和SA身份问题!
- 在ASP中,如何随机读取数据库记录,但在分页显示中又不会重新随机读取,仍然在那个记录集中翻页呢?
- 如何得知后台数据库中的table或view是否存在,即判断table或view是否存在的sql语句是什么?而不是返回出错提示!
- 求一条可行的sql查询语句
- 动态Sql语句的问题,谢谢大家了
- 菜鸟的触发器问题
店号 级别
1 1
2 4
3 3
while 总数>0
begin
if 总数-需要数>=0
begin
update 实际数=总数-需要数 ...
set 总数=总数-需要数
end
else
begin
update 实际数=总数
set 总数=0
end
end
insert into tb1
select 1,420 union all select 2,330 union all select 3,200
create table tb2(店号 int ,商品号 int,定货数 int,实际分到货数 int)
insert into tb2
select 1,1,50,0 union all select 2,2,400,0 union all select 3,1,40,0 union all select 3,2,301,0 union all select 3,3,209,0
create table tb3(店号 int,级别 int)
insert into tb3 select 1,1 union all select 2,4 union all select 3,3
select IDENTITY(int,1,1) id,tb2.*,tb1.商品总数 into #a from tb2,tb1,tb3 where tb1.商品号=tb2.商品号 and tb2.店号=tb3.店号 order by tb2.商品号,tb3.级别declare @gets int, @shanpinid int,@count int
set @count=0
update a set
@gets=case when @shanpinid=商品号 and (@count+定货数)<商品总数 then 定货数
when @shanpinid=商品号 and (@count+定货数)>商品总数 then 商品总数-@count
when @shanpinid<>商品号 and 定货数>商品总数 then 商品总数
else 定货数 end,
实际分到货数=@gets,@count=case when @shanpinid=商品号 then @count+@gets else @gets end,
@shanpinid=商品号
from #a aselect * from #a
店号 商品号 定货数 实际分到货数 商品总数
1 1 50 50 420
3 1 40 40 420
3 2 301 301 330
2 2 400 29 330
3 3 209 200 200
insert into tb1
select 1,420 union all select 2,330 union all select 3,200
create table tb2(店号 int ,商品号 int,定货数 int,实际分到货数 int)
insert into tb2
select 1,1,50,0 union all select 2,2,400,0 union all select 3,1,40,0 union all select 3,2,301,0 union all select 3,3,209,0
create table tb3(店号 int,级别 int)
insert into tb3 select 1,1 union all select 2,4 union all select 3,3
select 店号,
(select top 1 级别 from tb3 where 店号=tb2.店号) as 店等级,
商品号,
定货数,
(select sum(商品总数) from tb1 where 商品号=tb2.商品号 ) as 商品总数
--实际分到货数
into #F
from tb2 select *,
case when 剩余数 >=定货数 then 定货数
else case when 剩余数<=0 then 0 else 剩余数 End
end
as 实际分到数
from
(
select *,
商品总数-isnull((select sum(定货数) from #F where 商品号=A.商品号 And 店等级<A.店等级),0) as 剩余数
from #F A
) tmpA
order by 商品号店号 店等级 商品号 定货数 商品总数 剩余数 实际分到数
-------------------------------------------------------------------
1 1 1 50 420 420 50
3 3 1 40 420 370 40
3 3 2 301 330 330 301
2 4 2 400 330 29 29
3 3 3 209 200 200 200
from #F A
) tmpA
这两个地方不明白没用过呀,执教小弟一下吧
top 1什么意思呀,这不是只有一条数据了吗?