一张表T1
a        b       c
a001    b001     5
a001    b002     7
另一张表T2a        b       c    d  
a001    b001     5    10
a001    b002     7    20
a001    b002     7    30
如何查询得到结果:
a        b       c     e
a001    b001     5     10
a001    b002     7     50

解决方案 »

  1.   

    t1表有用吗?select a,b,c,sum(d) as e from t2
    group by a,b,c
      

  2.   

    select a.a, a.b, a.c, e=sum(b.d)
    from t1 a, t2 b
    where a.a=b.a and a.b=b.b and a.c=b.c
    group by a.a, a.b, a.c
      

  3.   

    select a.*,e=(select sum(d) from t2 where a=a.a and b=a.b and c=a.c) from t1 a order by a.a
      

  4.   

    好像你的T1表,没什么用啊
    select a,b,c,sum(d) from T2 group by a,b,c order by a,b,c
      

  5.   

    从结构上看,可这样设计一下表,才不至于造成数据冗余。(相同字段尽可能放在同一个表内)
    -------------------------------------------------------------------------------
    表T2
    a        b       c    d  
    a001    b001     5    10
    a001    b002     7    20
    a001    b002     7    30表T1
    a     d
    a001  10
    a001  20
    a001  30这样,表的数据不会分布在多表中,查询时,通过表T1,T2之间的共同字段a关键就行了..如果要求:
    select T2.a,T2.B,T2.C,sum(T1.d)
    from T1,T2
    where T1.a=T2.a
      

  6.   

    忘了将表T2中的数据减去了..呵呵,上解中,表T2中的D字段要减去..
      

  7.   

    按照这个SQL语句查询有重复数据发生
    select a.*,e=(select sum(d) from t2 where a=a.a and b=a.b and c=a.c) from t1 a order by a.aa        b       c     e
    a001    b001     5     10
    a001    b002     7     50
    a001    b002     7     50
    数据a001    b002     7     50发生重复!
    如何去除?
      

  8.   

    select distinct a.*,e=(select sum(d) from t2 where a=a.a and b=a.b and c=a.c) from t1 a order by a.a
      

  9.   

    但是A表的字段A是TXT类型的字符,不能用distinct