注册 登录
编程论坛 SQL Server论坛

要满足这样条件的 sql语句怎么写

lukebc 发布于 2016-10-19 16:25, 2407 次点击
我这样一张表 有字段 库位,件数,长,宽,高,挂衣,进仓时间(“挂衣”有两种状态 Y或N)
查询 如库位为“A”开头或“B"开头或"C"开头的为1库 "D"、“G”、“F”开头的为 2库
计算
当 1库“挂衣”=N 时在某段“进仓时间”内的立方总合(立方总合= sum( (长*宽*高/1000)*件数)
当1库 挂衣”=Y 时在某段“进仓时间”内"件数"的总合

库2 计算同上
请问我要分别计算在一段时间内 库1、库2 的立方总合和件数总合sql语句怎么写
3 回复
#2
mywisdom882016-10-19 17:34
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.挂衣

#3
mywisdom882016-10-20 14:02
--汇总也可以这样写,2步合在一起了。
declare @dt datetime
set @dt='2016-10-2'

select t1.库名,t1.挂衣,
sum(case when t1.挂衣='n' then t1.长*t1.宽*t1.高/1000.00*t1.件数 else 0 end) as 总方,
sum(case when t1.挂衣='y' then 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.挂衣
#4
泪落渊2016-10-20 18:07
select 库名,挂衣,
sum((case 挂衣 when N then (长*宽*高/1000)*件数 else 0 end)) as 立方总合,
sum((case 挂衣 when Y then 件数 else 0 end)) as 件数总合   
from
(select (case when substring(库位,1,1) in ('A','B','C') then '1库' else '2库' end) as 库名,件数,长,宽,高,挂衣,进仓时间 from 表)T
where  进仓时间 between begin_date and end_date
group by 库名,挂衣;
1