日期:2014-05-17  浏览次数:20482 次

如何显示当天所有产品的数量?
SQL code

----建立测试数据
----环境: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]      



已知表 T_testJxc
fdId fdNumber fdCz fdcf fdDate fdCheck
001 10.0 JH A仓 2012-07-01 已审核
001 -7.0 XL A仓 2012-07-01 已审核
002 10.0 JH A仓 2012-07-01 已审核
001 5.0 JH A仓 2012-07-02 已审核

我要的结果:(要显示每天所有产品的库存数量,即每一天没有进行 进出货 的所有编号产品也要显示出来)
日期 编号 仓库 期初库存 进货 出货 期末库存
2012-07-01 001 A仓 0 10.0 -7.0 3.0
2012-07-01 002 A仓 0 10.0 0.0 10.0
2012-07-02 001 A仓 3.0 5.0 0.0 8.0
2012-07-02 002 A仓 10.0 0.0 0.0 10.0
-------------------------------------------------------
这个查询如何写?








------解决方案--------------------
探讨

SQL code

select
b.日期 ,
c.编号 ,
c.仓库,

[期初库存]=isnull((select sum(fdNumber) from T_testJxc
where [fdId]=c.编号 and [fdcf]=c.仓库 and [fdDate]<b.日期)
,0),

sum(case when [fdCz]='JH' the……