数据更新表中有数据如下
ID   NAME   QTY   PRICE   TOTAL   STOCK
101  可乐   100   2.50    250     01
101  可我   200   2.60    520     02
102  雪碧   10    2.30    23      01
102  雪碧   20    2.40    48      02 
...
...请问如何那PRICE更新为平均价?
结果像这样ID   NAME   QTY   PRICE     TOTAL   STOCK
101  可乐   100   2.5667    2500    01
101  可我   200   2.5667    5200    02
102  雪碧   10    2.3667    23      01
102  雪碧   20    2.3667    48      02 
...
...

解决方案 »

  1.   

    update tb
    set price = (select avg(price) from tb where ID = t.ID)
    from tb t
      

  2.   

    create table tb(ID int,NAME varchar(10),QTY int,PRICE decimal(18,2),TOTAL int,STOCK varchar(10))
    insert into tb values(101 ,'可乐', 100 ,2.50 ,250 ,'01')
    insert into tb values(101 ,'可我', 200 ,2.60 ,520 ,'02')
    insert into tb values(102 ,'雪碧', 10  ,2.30 ,23  ,'01')
    insert into tb values(102 ,'雪碧', 20  ,2.40 ,48  ,'02')
    goupdate tb
    set price = (select avg(price) from tb where ID = t.ID)
    from tb tselect * from tbdrop table tb/*
    ID          NAME       QTY         PRICE                TOTAL       STOCK      
    ----------- ---------- ----------- -------------------- ----------- ---------- 
    101         可乐         100         2.55                 250         01
    101         可我         200         2.55                 520         02
    102         雪碧         10          2.35                 23          01
    102         雪碧         20          2.35                 48          02(所影响的行数为 4 行)
    */
      

  3.   

    create table tb(ID int,NAME varchar(10),QTY int,PRICE decimal(18,4),TOTAL int,STOCK varchar(10))
    insert into tb values(101 ,'可乐', 100 ,2.50 ,250 ,'01')
    insert into tb values(101 ,'可我', 200 ,2.60 ,520 ,'02')
    insert into tb values(102 ,'雪碧', 10  ,2.30 ,23  ,'01')
    insert into tb values(102 ,'雪碧', 20  ,2.40 ,48  ,'02')
    goupdate tb
    set price = (select sum(QTY*price)/sum(QTY) from tb where ID = t.ID)
    from tb tselect * from tbdrop table tb/*
    ID          NAME       QTY         PRICE                TOTAL       STOCK      
    ----------- ---------- ----------- -------------------- ----------- ---------- 
    101         可乐         100         2.5667               250         01
    101         可我         200         2.5667               520         02
    102         雪碧         10          2.3667               23          01
    102         雪碧         20          2.3667               48          02(所影响的行数为 4 行)
    */
      

  4.   

    select avg(PRICE) from tb group by IDupdate t
    set price = (select avg(PRICE) from tb where id=t.id)
    from tb t
      

  5.   

    select sum(PRICE*QTY)/sum(QTY) from tb group by IDupdate t
    set price = (select sum(PRICE*QTY)/sum(QTY) from tb where id=t.id)
    from tb t