三个表:
表1:商品信息表,表2:销售表,表3:进货表。
select  t1.商品名称 ,sum(t3.amount) as 进货支出,sum(t4.amount) as 销售收入
from 商品信息表 t1 
 left join 进货表 t3 on t1.商品名称=t3.商品名称
 left join 销售表 t4 on t1.商品名称=t4.商品名称
 group by t1.商品名称执行后,sum(t3.amount) 数据不正确,如果写成这样:select  t1.商品名称 ,sum(t3.amount) as 进货支出
from 商品信息表 t1 
 left join 进货表 t3 on t1.商品名称=t3.商品名称
 group by t1.商品名称执行取得的数据是正确的。
后来怀疑是不是将表2与表3的amount值累加了,经查又不是。在销售表(t4)中删除一笔交易,再查询,发现sum(t3.amount)的值变了,但是减少的数值不等于删除的数据。
莫名其妙
莫名其妙
莫名其妙
莫名其妙
莫名其妙

解决方案 »

  1.   

    连接后可能产生NUL值, 换成sum(isnull(t3.amount,0))   as   进货支出另外, 这么连接可能产生或减少了数据行。 建议用一个函数或子查询来统计值。
      

  2.   

    select  
          t1.商品名称 ,
          '进货支出'=(select isnull(sum(amount),0) from 进货表 where 商品名称=a.商品名称),
          '销售收入'=(select isnull(sum(amount),0) from 销售表 where 商品名称=a.商品名称)
    from 商品信息表 a
      

  3.   


    select
          distinct  
          t1.商品名称 ,
          '进货支出'=(select isnull(sum(amount),0) from 进货表 where 商品名称=a.商品名称),
          '销售收入'=(select isnull(sum(amount),0) from 销售表 where 商品名称=a.商品名称)
    from 商品信息表 a
      

  4.   

    不是吧,我在我这儿建了一个数据库,没问题的啊!数值是正确的,
    你用的什么数据库?实在不行你看看 字段amount的数据类型吧!
      

  5.   

    用的是SQL2000,字段类型没错,可能如1楼所说:这么连接可能产生或减少了数据行。
    用4楼方法试试看
    select  
          a.商品名称 ,
          '进货支出'=(select isnull(sum(amount),0) from 进货表 where 商品名称=a.商品名称),
          '销售收入'=(select isnull(sum(amount),0) from 销售表 where 商品名称=a.商品名称)
    from 商品信息表 a
      

  6.   

    晕,你的SQL语句有问题,你用了两遍left join  你的到的值会是实际值的倍数!
    fa_ge 的语句是对的!不过要修理一下!select
          distinct  
          a.商品名称 ,
          '进货支出'=(select isnull(sum(amount),0) from 进货表 where 商品名称=a.商品名称),
          '销售收入'=(select isnull(sum(amount),0) from 销售表 where 商品名称=a.商品名称)
    from 商品信息表 a
      

  7.   

    现在的问题是:
    select 语句中,还要用t3.amount与其它列进行运算,如:
    select a.商品名称   , 
      '进货支出'=(select   isnull(sum(amount),0)   from   进货表   where   商品名称=a.商品名称), 
      '销售收入'=(select   isnull(sum(amount),0)   from   销售表   where   商品名称=a.商品名称),
       t4.amount-t3.amount as 利润
    from   商品信息表   a 应该如何进行替换?
      

  8.   

    那就这样呗:
    select   a.商品名称       ,   
        '进货支出'=(select       isnull(sum(amount),0)       from       进货表       where       商品名称=a.商品名称),   
        '销售收入'=(select       isnull(sum(amount),0)       from       销售表       where       商品名称=a.商品名称), 
            ((select       isnull(sum(amount),0)       from       销售表       where       商品名称=a.商品名称)-
            (select       isnull(sum(amount),0)       from       进货表       where       商品名称=a.商品名称))   as   利润 
    from       商品信息表       a   
      

  9.   

    你数据量不大是没多大问题的!万把条SQL Server还是可以处理滴!
      

  10.   

    查询时用外连接是没有问题的,找一个SQLSERVER的书看一下查询语句的书写方式