日期:2014-05-17 浏览次数:20482 次
----建立测试数据 ----环境:MSSQL2000 if exists (select * from sysobjects where id = object_id(N'T_testJxc') and OBJECTPROPERTY(id, N'IsUserTable') = 1) begin drop table T_testJxc end CREATE TABLE [T_testJxc] ( [fdId] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [fdNumber] [float] NULL , [fdCz] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [fdcf] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [fdDate] [datetime] NULL , [fdCheck] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ) ON [PRIMARY] GO Insert T_Testjxc (fdId,fdNumber,fdCz,fdcf,fdDate,fdCheck) Values ( '001',1.000000000000000e+001,'JH','A仓','2012-07-01 00:00:00.000','已审核') Insert T_Testjxc (fdId,fdNumber,fdCz,fdcf,fdDate,fdCheck) Values ( '001',-7.000000000000000e+000,'XL','A仓','2012-07-01 00:00:00.000','已审核') Insert T_Testjxc (fdId,fdNumber,fdCz,fdcf,fdDate,fdCheck) Values ( '002',1.000000000000000e+001,'JH','A仓','2012-07-01 00:00:00.000','已审核') Insert T_Testjxc (fdId,fdNumber,fdCz,fdcf,fdDate,fdCheck) Values ( '001',5.000000000000000e+000,'JH','A仓','2012-07-02 00:00:00.000','已审核') select * from T_testJxc go --------------------以下是尝试作一个查询处理,但不是我所要 要求的结果 select convert(char(10),fdDate,120) as 日期, [fdId] as 编号, [fdcf] as 仓库, [期初库存]=isnull((select sum(fdNumber) from T_testJxc where [fdId]=a.[fdId] and [fdcf]=a.[fdcf] and [fdDate]<a.[fdDate]),isnull((select top 1 fdNumber from T_testJxc where [fdId]=a.[fdId] order by [fdDate]),0)), sum(case when [fdCz]='JH' then [fdNumber] else 0 end) as [进货], sum(case when [fdCz]='XL' then [fdNumber] else 0 end) as [出货], [期末库存]=(select SUM(fdNumber) from T_testJxc where [fdId]=a.[fdId] and [fdcf]=a.[fdcf] and [fdDate]<=a.[fdDate]) from T_testJxc a group by [fdDate],[fdId],[fdCf]