求助sql2000数据查询问题
设有一表进销表salecom格式如下
日期 编号 期初库存 进货 销售
yyyymmdd,comid ,stock,checkin,salesub
20070801 0001 0 20 8
20070802 0001 12 10 13
20070803 0001 9 30 16
...
20070801 002 12 30 10
.
.
.
现在需提取期初和期末库存进行进销分析
所需表动行结果如下:
月份 商品 期初库存 期末库存 进货 销售
200708 0001 0 23 60 37
200708 0002 12 32 30 10
.
.
-----------------------------------
求教高人查询代码,最好能用一条语句完成,谢谢先.
------解决方案------------------------创建测试数据
declare @t table(yyyymmdd varchar(10),comid varchar(10),stock int,checkin int,salesub int)
insert @t
select '20070801 ', '0001 ', 0, 20, 8 union all
select '20070802 ', '0001 ', 12, 10, 13 union all
select '20070803 ', '0001 ', 9, 30, 16 union all
select '20070801 ', '0002 ', 12, 30, 10
----查询
SELECT
月份 = left(yyyymmdd,6) ,
商品 = comid,
期初库存 = (select top 1 stock from @t where comid = a.comid ORDER BY yyyymmdd),
期末库存 = (select top 1 stock from @t where comid = a.comid ORDER BY yyyymmdd) + sum(isnull(checkin,0)-isnull(salesub,0)),
进货 = sum(checkin),
销售 = sum(salesub)
FROM @t as a GROUP BY left(yyyymmdd,6),comid
/*结果
月份 商品 期初库存 期末库存 进货 销售
-------------------------------------------------------
200708 0001 0 23 60 37
200708 0002 12 32 30 10
*/