日期:2014-05-18  浏览次数:20694 次

如何利用sql根据流水账生成月报表


流水账格式  
日期   仓库   货物名称   入/出库   数量(出库为负数)  

生成报表格式为某年某月报表  
仓库   货物名称   月初   月入库   月出库   月结存


------解决方案--------------------
--假设查询2006年12月报表
declare @month varchar(6)
set @month = '200612 '

select 仓库,货物名称,
月初 = (select sum(数量) from 流水账 where 货物名称 = a.货物名称 and convert(varchar(6),日期,112) < @month),
月入库 = (select sum(case when 数量 > 0 then 数量 else 0 end)
from 流水账
where 货物名称 = a.货物名称 and convert(varchar(6),日期,112) = @month),
月出库 = (select sum(case when 数量 < 0 then - 数量 else 0 end)
from 流水账
where 货物名称 = a.货物名称 and convert(varchar(6),日期,112) = @month),
月结存 = (select sum(数量) from 流水账 where 货物名称 = a.货物名称 and convert(varchar(6),日期,112) <= @month)
from 流水账 a


--因为以前的数据已经不能再发生变化,所以建议楼主把数据导出到另外一个表
查询的时候直接查速度会快很多!