有A、B两张表,如下:A
id    number    price 
1001   10       100.0
1002   5        300.0
B
id     eid     cash
2001   1001    500.0
2002   1001    300.0通过一个sql语句查询出如下结果,A表有多少条记录,结果集就有几条记录A.id     amount                in     left  
1001     1000(number*price)    800    200(amount-in)
1002     1500                  0      1500

解决方案 »

  1.   

    select a.id,a.number*a.price,nz(b.in,0),a.number*a.price-nz(b.in,0) as left
    from a
    left join
    (select eid,sum(cash) as in from b group by eid) b
      

  2.   

    select A.id,A.number*A.price as amount,nz(c.sCash,0) as [in],A.number*A.price-nz(c.sCash,0) as [left]
    from A left join (select eid,sum(cash) as sCash from B group by eid) c on a.id=c.eid
        [align=center]====  ====
    [/align]
      

  3.   

    select a.id,a.number*a.price,if(isnull(b.in),0,b.in),a.number*a.price-if(isnull(b.in),0,b.in) as left
    from a
    left join
    (select eid,sum(cash) as in from b group by eid) b
      

  4.   

    呵呵,楼主是MYSQLselect a.id,a.number*a.price,if(isnull(b.in),0,b.in),a.number*a.price-if(isnull(b.in),0,b.in) as left
    from a
    left join
    (select eid,sum(cash) as in from b group by eid) b
    on a.id=B.eid
      

  5.   

    由于您有部分未结贴,所以特此介绍一下结贴的方法如果您问题已经得解决,请您及时结帖给分,以感谢帮助您的朋友。 结帖方法:点击版面右上方或右下方 [管理] ,进入页面后就可以输入密码,分别给分,结帖。 
     或参考:
    http://www.csdn.net/help/over.asp
    http://topic.csdn.net/u/20080110/19/7cb462f1-cac6-4c28-848e-0a879f4fd642.html
    =============================================================================
    问题解决,请及时结贴。  
     正确结贴方法:    
     管理帖子-->给分-->输入密码-->结贴
        [align=center]====  ====
    [/align]
      

  6.   

    更近一步,如果要把那些remaining>0的纪录选出来应该怎么改?
      

  7.   

    select A.id,A.number*A.price as amount,IFNULL(c.sCash,0) as `in`,A.number*A.price-IFNULL(c.sCash,0) as `left`
    from A left join (select eid,sum(cash) as sCash from B group by eid) c on a.id=c.eid
    where A.number*A.price-IFNULL(c.sCash,0) >0;
        [align=center]====  ====
    [/align]