数据更新表中有数据如下
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
...
...
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
...
...
set price = (select avg(price) from tb where ID = t.ID)
from tb t
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 行)
*/
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 行)
*/
set price = (select avg(PRICE) from tb where id=t.id)
from tb t
set price = (select sum(PRICE*QTY)/sum(QTY) from tb where id=t.id)
from tb t