27,579
社区成员
发帖
与我相关
我的任务
分享
select 客户名称,产品品名,
前日结存数量 =(select sum(case when 入出库='入库' then 交货数量 else 0 end), -sum(case when 入出库='出库' then 交货数量 else 0 end) from tb where 客户名称 = 'A' and 产品品名 = 'A01' and 登记日期<'2010-05-20'),--(登记日期前一天以前的入库的交货数量合计-出库的交货数量合计),
本日入库数量 = sum(case when 入出库='入库' then 交货数量 else 0 end),--(登记日期那天的入库数量合计),
本日出库数量 = sum(case when 入出库='出库' then 交货数量 else 0 end),--(登记日期那天的出库数量合计),
本日结存数量 = sum(case when 入出库='入库' then 交货数量 else 0 end) - sum(case when 入出库='出库' then 交货数量 else 0 end) --(前日结存数量+本日入库数量-本日出库数量)
from tb
where 客户名称 = 'A' and 产品品名 = 'A01' and 登记日期='2010-05-20'
group by 客户名称,产品品名,登记日期
select a.客户名称,a.产品品名,
前日结存数量 =(select sum(case when 入出库='入库' then 交货数量 else 0 end) -
sum(case when 入出库='出库' then 交货数量 else 0 end)
from tb where 客户名称 = a.客户名称 and 产品品名 = a.产品品名 and 登记日期<'2010-05-20'),--(登记日期前一天以前的入库的交货数量合计-出库的交货数量合计),
本日入库数量 = sum(case when 入出库='入库' then 交货数量 else 0 end),--(登记日期那天的入库数量合计),
本日出库数量 = sum(case when 入出库='出库' then 交货数量 else 0 end),--(登记日期那天的出库数量合计),
本日结存数量 = (select sum(case when 入出库='入库' then 交货数量 else 0 end) -
sum(case when 入出库='出库' then 交货数量 else 0 end)
from tb where 客户名称 = a.客户名称 and 产品品名 = a.产品品名 and 登记日期<='2010-05-20') --(前日结存数量+本日入库数量-本日出库数量)
from (select distinct 客户名称,产品品名 from tb) a left join tb t on a.客户名称=t.客户名称 and t.登记日期='2010-05-20'
group by a.客户名称,a.产品品名,t.登记日期
/*
客户名称 产品品名 前日结存数量 本日入库数量 本日出库数量 本日结存数量
---- ---- ----------- ----------- ----------- -----------
A A1 30 10 5 35
B B1 30 10 5 35
C C1 30 0 0 30
D D1 30 0 0 30
(所影响的行数为 4 行)
*/
create table tb(
入出库 varchar(4), 客户名称 varchar(4),产品品名 varchar(4), 交货数量 int, 登记日期 datetime)
insert into tb
select '入库',' A',' A1', 30 ,'2010-05-19' union all
select '入库',' A',' A1', 10 ,'2010-05-20' union all
select '出库',' A',' A1', 5 ,'2010-05-20' union all
select '入库',' B',' B1', 30 ,'2010-05-19' union all
select '入库',' B',' B1', 10 ,'2010-05-20' union all
select '出库',' B',' B1', 5 ,'2010-05-20'
select 客户名称,产品品名,
前日结存数量 =(select sum(case when 入出库='入库' then 交货数量 else 0 end) -
sum(case when 入出库='出库' then 交货数量 else 0 end)
from tb where 客户名称 = t.客户名称 and 产品品名 = t.产品品名 and 登记日期<'2010-05-20'),--(登记日期前一天以前的入库的交货数量合计-出库的交货数量合计),
本日入库数量 = sum(case when 入出库='入库' then 交货数量 else 0 end),--(登记日期那天的入库数量合计),
本日出库数量 = sum(case when 入出库='出库' then 交货数量 else 0 end),--(登记日期那天的出库数量合计),
本日结存数量 = (select sum(case when 入出库='入库' then 交货数量 else 0 end) -
sum(case when 入出库='出库' then 交货数量 else 0 end)
from tb where 客户名称 = t.客户名称 and 产品品名 = t.产品品名 and 登记日期<='2010-05-20') --(前日结存数量+本日入库数量-本日出库数量)
from tb t
where 登记日期='2010-05-20'
group by 客户名称,产品品名,登记日期
/*客户名称 产品品名 前日结存数量 本日入库数量 本日出库数量 本日结存数量
---- ---- ----------- ----------- ----------- -----------
A A1 30 10 5 35
B B1 30 10 5 35
(所影响的行数为 2 行)
*/
drop table tb