Sql server 表中的导出和导入库存仓库
我有一个sql中有4列的表(键ID): 我想连续计算存货,但不是预期的结果。 你能帮我得到如下结果吗?带列清单Sql server 表中的导出和导入库存仓库,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我有一个sql中有4列的表(键ID): 我想连续计算存货,但不是预期的结果。 你能帮我得到如下结果吗?带列清单 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
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
在2008年,你错过了上的总和(),但是还有另一个选择 示例
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
使用联接还有窗口功能,但这在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
declare@T表(id int-identity主键,import int,export int);
在@T(导入、导出)值中插入
(1333, 0)
, (0, 368)
, (0, 252)
, (1965, 0)
, (0, 162)
, (0, 551)
, (0 , 69);
选择t1.id、t1.import、t1.export
,总计(t2.导入-t2.导出)为inven
从@T t1开始
加入@T t2
在t2.id上,我使用了上面的代码,但出现了错误:“'order'附近的语法不正确”。@MrTrung在我的计算机上工作。对不起,我帮不了你这么多。@trung先生很乐意帮忙
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
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