update a
set 装苹果数=b.cnt
from 箱子 a,(select 所在箱子ID,count(*) as cnt from 苹果 group by 所在箱子ID)b
where a.ID=b.所在箱子ID

解决方案 »

  1.   

    用update的話,首先你要幫表加個字段
    alter table 蘋果 add 装苹果数 int
      

  2.   

    --或者:
    update a set 装苹果数=(select count(*) from 苹果 where 所在箱子ID=a.ID)
    from 箱子 a
    --或者:
    update 箱子 set 装苹果数=(select count(*) from 苹果 where 苹果.所在箱子ID=箱子.ID)
      

  3.   

    Update A Set 装苹果数=(Select Count(*) from 苹果 Where 所在箱子ID=A.ID) from 箱子 A
      

  4.   

    --或者:
    update a set 装苹果数=(select count(*) from 苹果 where 所在箱子ID=a.ID)
    from 箱子 a
    --或者:
    update 箱子 set 装苹果数=(select count(*) from 苹果 where 苹果.所在箱子ID=箱子.ID)可以得出正确的结果,但是下面这句却执行不了
    update a
    set 装苹果数=b.cnt
    from 箱子 a,(select 所在箱子ID,count(*) as cnt from 苹果 group by 所在箱子ID)b
    where a.ID=b.所在箱子IDMsg 102, Level 15, State 1:
    Line 1:
    Incorrect syntax near '('.
    Msg 102, Level 15, State 1:
    Line 1:
    Incorrect syntax near 'b'.不知为何?