create table t--出入库表
(
id int identity(1,1),
type varchar(50),--类别
mc varchar(50),--名称
xh varchar(50),--型材型号
c decimal(13,3)default 0,--长(米)
k decimal (13,3)default 0,--宽(米)
h decimal(13,1)default 0,--厚(毫米)
gg varchar(50),--规格
dj decimal(13,2)default 0,--单价
sl int default 0, --数量
status char(1),--状态(1为入库,0为出库)
rq datetime --日期
)
insert into t select '板材','钢板',null,6,1.2,3,'6*1.2*3',1000,10,'1','2006-1-1'--钢板入库insert into t select '板材','钢板',null,1,1.2,3,'6*1.2*3',1000,1,'0','2006-1-1'--钢板出库--要求得到结余的库存材料明细
/*
材料类别 名称 型号 长 宽 厚 规格 单价 数量
板材 钢板 null 6 1.2 3 6*1.2*3 1000 9
板材 钢板 null 5 1.2 3 6*1.2*3 1000 1
*/
drop table t
(
id int identity(1,1),
type varchar(50),--类别
mc varchar(50),--名称
xh varchar(50),--型材型号
c decimal(13,3)default 0,--长(米)
k decimal (13,3)default 0,--宽(米)
h decimal(13,1)default 0,--厚(毫米)
gg varchar(50),--规格
dj decimal(13,2)default 0,--单价
sl int default 0, --数量
status char(1),--状态(1为入库,0为出库)
rq datetime --日期
)
insert into t select '板材','钢板',null,6,1.2,3,'6*1.2*3',1000,10,'1','2006-1-1'--钢板入库insert into t select '板材','钢板',null,1,1.2,3,'6*1.2*3',1000,1,'0','2006-1-1'--钢板出库--要求得到结余的库存材料明细
/*
材料类别 名称 型号 长 宽 厚 规格 单价 数量
板材 钢板 null 6 1.2 3 6*1.2*3 1000 9
板材 钢板 null 5 1.2 3 6*1.2*3 1000 1
*/
drop table t
from t
group by type,mc,xh,c,k,h,gg,dj
from
(select *,数量 ss from t where status='1'
Union all
select *,-数量 ss from t where status='0'
) a
group by 材料类别,名称,型号,长,宽,厚,规格
-------------------------
板材 钢板 NULL 1.000 1.200 3.0 6*1.2*3 1000.00 NULL
板材 钢板 NULL 6.000 1.200 3.0 6*1.2*3 1000.00 10
------------------------------------
板材 钢板 NULL 1.000 1.200 3.0 6*1.2*3 1
板材 钢板 NULL 6.000 1.200 3.0 6*1.2*3 10
from t
group by type,mc,xh,c,k,h,gg,dj
from t
group by type,mc,xh,c,k,h,gg,dj
板材 钢板 null 6 1.2 3 6*1.2*3 1000 10
板材 钢板 null 1 1.2 3 6*1.2*3 1000 -1
结果应该:材料类别 名称 型号 长 宽 厚 规格 单价 数量
板材 钢板 null 6 1.2 3 6*1.2*3 1000 10
板材 钢板 null 1 1.2 3 6*1.2*3 1000 -1
------------------------------
不对,要的结果是这样:材料类别 名称 型号 长 宽 厚 规格 单价 数量
板材 钢板 null 6 1.2 3 6*1.2*3 1000 9
板材 钢板 null 5 1.2 3 6*1.2*3 1000 1
from #t where id!>a.id and type=a.type and mc=a.mc)
from #t a
id type mc xh c k h gg dj sl status rq 库存
----------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------- --------------- --------------- -------------------------------------------------- --------------- ----------- ------ ------------------------------------------------------ -----------
1 板材 钢板 NULL 6.000 1.200 3.0 6*1.2*3 1000.00 10 1 2006-01-01 00:00:00.000 10
2 板材 钢板 NULL 1.000 1.200 3.0 6*1.2*3 1000.00 1 0 2006-01-01 00:00:00.000 9(所影响的行数为 2 行)
复制记事本可以看到结果
1 板材 钢板 NULL 6.000 1.200 3.0 6*1.2*3 1000.00 10 1 2006-01-01 00:00:00.000 10
2 板材 钢板 NULL 1.000 1.200 3.0 6*1.2*3 1000.00 1 0 2006-01-01 00:00:00.000 9