读书人

怎么利用sql根据流水账生成月报表

发布时间: 2012-01-18 00:23:26 作者: rapoo

如何利用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


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

读书人网 >SQL Server

热点推荐