我在sql(密钥ID)中有一个包含4列的表:
ID Items Import Export
1 A1 1333 0
2 A1 0 368
3 A1 0 252
4 A1 1965 0
5 A1 0 162
6 A1 0 551
7 A1 0 69
我想连续计算库存商品。但不是预期的结果。 你可以帮我看到如下结果吗?使用列库存
ID Items Import Export Inventory
1 A1 1333 0 1333
2 A1 0 368 965
3 A1 0 252 713
4 A1 1965 0 2678
5 A1 0 162 2516
6 A1 0 551 1965
7 A1 0 69 1896
这是我的代码:
Select ID,
(A.Invent + Import-Sum(Export)) as Inventory
From MyColumn,
(
Select Top 1 (Import - Export) as Invent
From MyColumn
Where Items in ('A1')
) as A
Where Items in ('A1')
Group by
A.Invent,
Import,ID
答案 0 :(得分:1)
2008年你错过了 sum(),但还有另一种选择
示例强>
Declare @YourTable Table ([ID] int,[Items] varchar(50),[Import] int,[Export] int)
Insert Into @YourTable Values
(1,'A1',1333,0)
,(2,'A1',0,368)
,(3,'A1',0,252)
,(4,'A1',1965,0)
,(5,'A1',0,162)
,(6,'A1',0,551)
,(7,'A1',0,69)
Select A.*
,B.*
from @YourTable A
Cross Apply (
Select Inventory = sum(Import-Export)
From @YourTable
Where Items=A.Items and ID<=A.ID
) B
<强>返回强>
ID Items Import Export Inventory
1 A1 1333 0 1333
2 A1 0 368 965
3 A1 0 252 713
4 A1 1965 0 2678
5 A1 0 162 2516
6 A1 0 551 1965
7 A1 0 69 1896
答案 1 :(得分:0)
使用连接
也是窗口功能,但这在2008年不可用
declare @T table (id int identity primary key, import int, export int);
insert into @T (import, export) values
(1333, 0)
, (0, 368)
, (0, 252)
, (1965, 0)
, (0, 162)
, (0, 551)
, (0 , 69);
select t1.id, t1.import, t1.export
, sum(t2.import - t2.export) AS inven
from @T t1
join @T t2
on t2.id <= t1.id
group by t1.id, t1.import, t1.export
order by t1.id
select *
, sum(import - export) over (order by t.id) as inven
from @T t;
id import export inven
----------- ----------- ----------- -----------
1 1333 0 1333
2 0 368 965
3 0 252 713
4 1965 0 2678
5 0 162 2516
6 0 551 1965
7 0 69 1896