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

盘点表的自动生成!
一个表是投料的:
CGHB
识别码 投料数量 投料日期
7102011 6 2007-1-5
7101211 12 2007-8-10
7097101 5 2007-8-20
7097201 10 2007-9-10
7094201 100 2007-9-30

一个是交付表:
MGHB
识别码 交付数量 交付日期
7097101 4 2007-8-20
7097201 10 2007-9-10
7094201 95 2007-9-30

用SQL语句取得下列结果:
识别码 交付数量 交付日期
7102011 6 2007-1-5
7101211 12 2007-8-10
7097101 1 2007-8-20
7094201 5 2007-9-30
我用的是ACCESS数据库,有几个月的数据,请考虑速度问题!
先谢谢大家了!


------解决方案--------------------
declare @CGHB table (sbm varchar(10),tlsl int,tlrq datetime)
insert into @cghb select '7102011',6,'2007-1-5' 
union all select '7101211',12,'2007-8-10' 
union all select '7097101',5,'2007-8-20' 
union all select '7097201',10,'2007-9-10' 
union all select '7094201',100,'2007-9-30' 

declare @MGHB table (sbm varchar(10),jfsl int,jfrq datetime) 
insert into @mghb select '7097101',4,'2007-8-20'
union all select '7097201',10,'2007-9-10'
union all select '7094201',95,'2007-9-30' 

select sbm,convert(varchar(10),rq,111),sum(sl) sl from (
select sbm,tlsl sl,tlrq rq from @cghb union all
select sbm,-jfsl sl,jfrq rq from @mghb)a group by sbm,rq
------解决方案--------------------
--Access 使用的是jet-SQL,SQL Server用的是T-SQL。

--Access下的SQL语句:

select 识别码,sum(num) as 交付数量,max(dt) as 交付日期
from 
(
SELECT 识别码, 投料数量 as num, 投料日期 as dt
FROM CGHB
union all
SELECT 识别码, 交付数量*(-1) as num, 交付日期 as dt
FROM MGHB 
) as t
group by 识别码
having sum(num)<>0
------解决方案--------------------
SQL code


--CSDN自动在<>中间加了空格,你需要手工把空格删掉。

--Access 使用的是jet-SQL,SQL Server用的是T-SQL。 

--Access下的SQL语句: 

select 识别码,sum(num) as 交付数量,max(dt) as 交付日期 
from  
( 
    SELECT 识别码, 投料数量 as num, 投料日期 as dt 
    FROM CGHB 
    union all 
    SELECT 识别码, 交付数量*(-1) as num, 交付日期 as dt 
    FROM MGHB  
) as t 
group by 识别码 
having sum(num) <>0

------解决方案--------------------
select ghb.识别码, ghb.投料数量-mghb.交付数量 as 交付数量,mghb.交付日期
from ghb,mghb where ghb.识别码=mghb.识别码 and ghb.投料数量-mghb.交付数量>0
union
select * from ghb where not exists(select * from mghb where 识别码=ghb.识别码)