回复人: zjcxc(邹建) ( ) 信誉:155  2003-11-4 20:36:20  得分:0 
  
insert into A(时间,部门,工艺,product_id)
select 时间,部门,工艺,product_id
from(
SELECT max(createtime) as 时间
,storage.bumen as 部门
,product_id
,storage.gongyi as 工艺
,product.product as 产品名称
FROM storage INNER JOIN  product 
ON storage.product_id = product.ID
group by product.product,storage.gongyi  , product_id  ,storage.bumen
having sum(storage.product_ru-storage.product_chu-storage.baofei)=0
) a
where not exists(select 1 from A where 时间=a.时间,部门=a.部门,工艺=a.工艺,product_id=a.product_id)以上是zjcxc(邹建)大侠给的答案。
但是我用过之后发现,当A表什么记录都没有的时候是可以插入全部记录为0的数据,但是当A表最起码有一个记录的时候,就算记录数有几百都是插不进去的。请各位是什么问题?

解决方案 »

  1.   

    insert A(时间,部门,工艺,product_id)
    select 时间,部门,工艺,product_id
    from(
    SELECT max(createtime) as 时间
    ,storage.bumen as 部门
    ,product_id
    ,storage.gongyi as 工艺
    ,product.product as 产品名称
    FROM storage JOIN  product 
    ON storage.product_id = product.ID
    group by product.product,storage.gongyi  , product_id  ,storage.bumen
    having sum(storage.product_ru-storage.product_chu-storage.baofei)=0
    ) a
    where not exists(select 1 from A where 时间=a.时间 and 部门=a.部门 and 工艺=a.工艺 and product_id=a.product_id)
      

  2.   

    --条件语句写错了,将,换成and就成了.insert into A(时间,部门,工艺,product_id)
    select 时间,部门,工艺,product_id
    from(
    SELECT max(createtime) as 时间
    ,storage.bumen as 部门
    ,product_id
    ,storage.gongyi as 工艺
    ,product.product as 产品名称
    FROM storage INNER JOIN  product 
    ON storage.product_id = product.ID
    group by product.product,storage.gongyi  , product_id  ,storage.bumen
    having sum(storage.product_ru-storage.product_chu-storage.baofei)=0
    ) a
    where not exists(select 1 from A where 时间=a.时间 and 部门=a.部门 and 工艺=a.工艺 and product_id=a.product_id)
      

  3.   

    --这下做了测试,不会有问题了.declare @a table(时间 datetime,部门 varchar(10),工艺 varchar(10),product_id int)insert into @a
    select getdate(),'A部门','A工艺',1
    union all select getdate(),'B部门','B工艺',2insert into @a(时间,部门,工艺,product_id)
    select 时间,部门,工艺,product_id
    from (
    select 时间=getdate(),部门='A部门',工艺='A工艺',product_id=1
    union all select getdate(),'C部门','C工艺',3
    ) a
    where not exists(select 1 from @a where 时间=a.时间 and 部门=a.部门 and 工艺=a.工艺 and product_id=a.product_id)select * from @a
      

  4.   

    多谢各位大侠。是我错了,我在A表中加多了一个字段ID。删除之后就行啦!