日期 进出分类 品项 数量 金额
10月1日 采购入库 红油漆 10 100
10月15日 销售 红油漆 5 50
11月2日 采购入库 红油漆 20 200
11月22日 销售 红油漆 10 100

如何以日期作为过滤条件,生成
品名 期初数量 期初金额 采购数量 采购金额 销售数量 销售金额 结存数量 结存金额
红油漆

解决方案 »

  1.   

    select 品项 as 品名,sum(case when 日期<@开始日期 then (case when 分类='销售' then 数量*-1 else 数量 end) else 0 end) as 起初数量,
    sum(case when 日期<@开始日期 then (case when 分类='销售' then 金额*-1 else 金额 end) else 0 end) as 起初金额,
    sum(case when 日期>=@开始日期 and 分类='采购入库' then 数量  else 0 end) as 采购数量,
    sum(case when 日期>=@开始日期 and 分类='采购入库' then 金额  else 0 end) as 采购金额,
    sum(case when 日期>=@开始日期 and 分类='销售' then 数量  else 0 end) as 销售数量,
    sum(case when 日期>=@开始日期 and 分类='销售' then 金额  else 0 end) as 销售金额,
    sum(case when 日期<=@截止日期 then (case when 分类='销售' then 数量*-1 else 数量 end) else 0 end) as 结存数量
    sum(case when 日期<=@截止日期 then (case when 分类='销售' then 金额*-1 else 金额 end) else 0 end) as 结存金额
    from tablename
    where 日期<=@截止日期
    group by 品项