2010-12-14 77 views
0

百分比计算研究我有一个这样的表:更新与同桌

ItemID  PersonID Score  Percentage 
========================================== 
1    1  10   [ = 10/10+30 = 25%] 
1    2  30   [ = 30/10+30 = 75%] 
2    1  20   [ = 20/20+40 = 33%] 
2    2  40   [ = 40/20+40 = 67%] 

的“百分比”中的数据没有进入,但是自动计算的,在一定的时间间隔。 计算是百分比=分数/总项目ID分数

而不是使用“选择做数学更新”方法,我试图编写单个SQL来更新“百分比”。

我想什么是这样的:

UPDATE tb_temp AS t1 
    SET t1.Percentage = 
     CEIL(t1.Score/
      (SELECT SUM(t2.Score) FROM tb_temp AS t2 WHERE t2.ItemID = t1.ItemID) 
     ); 

但它不工作(错误代码:1093你不能指定FROM子句中更新目标表“T1”)。

有什么想法?

+0

随着'CEIL()',你会得到'34%'和'67%''为条目ID = 2'。 – Danosaure 2010-12-14 11:14:56

+0

thx提醒....我会使用ROUND()来代替。 – LazNiko 2010-12-14 11:26:27

回答

-1

尝试:

UPDATE tb_temp t1 
    JOIN (SELECT ItemId, SUM(t2.Score) TotalScore 
      FROM tb_temp 
      group by ItemId) t2 ON t2.ItemID = t1.ItemID 
    SET t1.Percentage = CEIL(t1.Score/t2.TotalScore) 
+0

错误1054(42S22):'字段列表'中的未知列't2.Score' – Danosaure 2010-12-14 11:03:57

+0

假设@Michael Pakhantsov想要写:'更新tb_temp t1内部连接(从tb_temp中选择tt.ItemID,sum(tt.Score)TotalScore tt (tT.ItemId)t2使用(ItemID)设置t1.Percentage = CEIL(t1.Score/t2.TotalScore * 100)'(假设'Percentage int')。 – Danosaure 2010-12-14 11:08:44

+0

@Danosaure:您的修改版本按预期工作〜thx! – LazNiko 2010-12-14 11:25:44

0
UPDATE tb_temp AS t1 
    SET t1.Percentage = 
     CEIL(t1.Score/
      (SELECT SUM(t2.Score) FROM tb_temp AS t2 left join tb_temp AS t3 on t2.ItemID = t3.ItemID) 
     ); 
+0

你甚至试过你的陈述吗? – Danosaure 2010-12-14 11:01:56

+0

@Danosaure纠正 – 2010-12-14 11:04:20

+0

我再说一遍......你有没有尝试过你的“纠正”陈述? – Danosaure 2010-12-14 11:10:45