现在有2个表,如下:
   表ictemp
 busno      RTM
 1001       350
 1002       240
 1003       280  表income
 busno       drvno      icincome
 1001         001             
 1002         002
 1002         003
 1002         006
 1003         004
 1003         005    我想根据income表中相同busno的记录数来平均分配ictemp表中的RTM字段的值,并插入到income表的icincome字段中,比如,busno=1001的记录只有一条,那么其对应的icincome就应该是350,busno=1002的记录有3条,那么对应的icincome就应该是240/3=80,busno=1003的记录有2条,那么对应的icincome就应该是280/2=140……这个SQL语句应该怎么写?我试了很久没试出来……

解决方案 »

  1.   

    update i
      set icincome=r.rtm/t.ct
    from icincome i,(
    select busno,count(drvno) as ct
    from income
    group by busno
    ) as t,ictemp r
    where i.busno=t.busno
    and i.busno=r.busno
      

  2.   

    create table ictemp (busno int,rtm int)
    insert into ictemp select 1001 ,350
    insert into ictemp select 1002 ,240
    insert into ictemp select 1003 ,280create table income(busno int,drvno int,icincome int)
    insert into income select 1001,1,null
    insert into income select 1002,2,null
    insert into income select 1002,3,null
    insert into income select 1002,6,null
    insert into income select 1003,4,null
    insert into income select 1003,5,null
    go
    update t2 set icincome=t1.rtm/(select count(1) from income where busno=t2.busno) 
    from income t2 inner join ictemp t1 on t2.busno=t1.busnoselect * from incomedrop  table ictemp
    drop table income
    busno       drvno       icincome    
    ----------- ----------- ----------- 
    1001        1           350
    1002        2           80
    1002        3           80
    1002        6           80
    1003        4           140
    1003        5           140
      

  3.   

    我想问问playwarcraft():
    select count(1) from income where busno=t2.busno
    这句,count(1)是什么意思?用了count()怎么可以不用group by子句的?