MySQL划分两行并添加到新列中

时间:2013-07-07 08:13:05

标签: mysql

我有一个MYSQL表,我想在其中执行以下操作。

ID     Com      Com_Sub Year    Parameter       Value
6       A       A1     2010     Profit      33766.18
20      A       A1     2010     Revenues    2793617.12
30      A       A1     2011     Profit      84310.73
54      A       A1     2009     Profit      129129.5284
60      A       A1     2011     Revenues    2049157.294
70      B       B1     2010     Profit      3753765490
76      B       B1     2010     Revenues    217326.7561

现在我需要操纵它并使它像这样

ID     Com      Com_Sub Year    Parameter       Value          New Value
6       A        A1     2010    Profit         33766.18       0.0123
20      A        A1     2010    Revenues       2793617.12
30      A        A1     2011    Profit         84310.73       0.0252
54      A        A1     2009    Profit         129129.5284    
60      A        A1     2011    Revenues       2049157.294
70      B        B1     2010    Profit         3753765490     1.235
76      B        B1     2010    Revenues       217326.7561

这意味着每当我在行中有共同的Year和Common Com_sub值时,我需要添加两个值的除法。

2 个答案:

答案 0 :(得分:0)

假设该表名为nanuet,则应执行此操作:

alter table nanuet add newvalue decimal(6,2);

update nanuet n1 join nanuet n2 on n1.c1=n2.c1
    set n1.newvalue = n1.value/n2.value
    where n1.id<n2.id;

如果有超过2行具有相同的c1值,则结果难以预测。

答案 1 :(得分:0)

    UPDATE tbl t1
       SET t1.new_col_name = t1.Value / t2.Value
INNER JOIN tbl t2 ON t2.Com_Sub = t1.Com_Sub
                 AND t2.Year = t1.Year 
                 AND t2.Parameter = 'Revenues'
     WHERE t1.Revenues = 'Profit'