select 产品名称,日期,收发类型,入库数=case 收发类型 when '入库 ' then 数量 end, 出库数=case 收发类型 when '出库 ' then 数量 end, [结存]=(select sum(case 收发类型 when '入库 ' then 数量 else -数量 end) from test where 日期 <=a.日期) from test a
create table t (产品名称 varchar(10), 时间类型 varchar(10), 数量 smallint) insert into t select 'aaa ', '入库 ',1000 union all select 'bbb ', '出库 ',20 union all select 'aaa ', '出库 ',50
select a.*,(入库数量+出库数量)as 结存 from ( select 产品名称,sum(case when 时间类型= '入库 ' then 数量 else 0 end)as 入库数量, sum(case when 时间类型= '出库 ' then -数量 else 0 end )as 出库数量 from t group by 产品名称 )a