if object_id('tempdb..#tb') is not null drop table #tb
go
create table #tb(库位 varchar(5),件数 int,长 numeric(4,2),宽 numeric(4,2),高 numeric(4,2),挂衣 varchar(2),进仓时间 datetime)
insert into #tb
select 'a001',10,10,20,30,'y','2016-10-1' union all
select 'a001',20,10,10,30,'y','2016-10-2' union all
select 'a001',10,3,4,5,'y','2016-10-2' union all
select 'b001',10,3,4,5,'y','2016-10-3' union all
select 'b001',10,1,2,3,'y','2016-10-4' union all
select 'c002',10,1,2,3,'y','2016-10-4' union all
select 'd003',10,3,2,3,'y','2016-10-1' union all
select 'g003',10,1,2,3,'y','2016-10-2' union all
select 'b003',10,1,2,3,'y','2016-10-6' union all
select 'f003',10,5,2,3,'y','2016-10-3' union all
select 'a001',10,2,3,4,'n','2016-10-1' union all
select 'a001',10,3,4,5,'n','2016-10-2' union all
select 'b001',10,3,4,5,'n','2016-10-3' union all
select 'b001',10,1,2,3,'n','2016-10-4' union all
select 'c002',10,1,2,3,'n','2016-10-4' union all
select 'd003',10,1,2,3,'n','2016-10-1' union all
select 'g003',10,4,2,3,'n','2016-10-2' union all
select 'b003',10,1,2,3,'n','2016-10-6' union all
select 'f003',10,3,2,3,'n','2016-10-3'
declare @dt datetime
set @dt='2016-10-2'
select t1.库名,t1.挂衣,
case when t1.挂衣='n' then sum(t1.长*t1.宽*t1.高/1000.00*t1.件数) else 0 end as 总方,
case when t1.挂衣='y' then sum (t1.件数) else 0 end as 总件 from
(select (case when substring(库位,1,1) in('a','b','c') then '1库' else '2库' end)as 库名,件数,长,宽,高,挂衣,进仓时间 from #tb
where 进仓时间 <=@dt
)t1
group by t1.库名,t1.挂衣