2014-01-11 75 views
1

我有2個表,我試圖更新首先使用2日table.Below聚合函數的代碼: -更新使用從另一個表彙總值表的多個列

Update temp1 t1 
    set t1.Margin = SUM(t2.Margin2), 
    t1.Revenue = SUM(t2.Revenue2), 
    t1.Sales = SUM (t2.Sales2), 
    t1.Revenue = SUM (t2.Revenue2) 

    from t1 inner join tempcost t2 
    on t1.P_Id = t2.P_Id 

顯示錯誤「聚合可能不會出現在UPDATE語句的集合列表中」。 有關如何實現此目的的任何建議。

+0

你使用MySQL或SQL Server? –

+0

使用Sql Server。 – Shivam657

回答

4

的正確語法在MySQL:

Update temp1 t1 join 
     (select p_id, SUM(t2.Margin2) as margin2, SUM(t2.Revenue2) as revenue2, 
       SUM(t2.Sales2) as sales2 
     from tempcost t2 
     group by p_id 
     ) t2 
     on t1.P_Id = t2.P_Id 
    set t1.Margin = t2.margin2, 
    t1.Revenue = t2.Revenue2, 
    t1.Sales = t2.Sales2; 

的正確語法在SQL Server:

Update t1 
    set Margin = t2.margin2, 
     Revenue = t2.Revenue2, 
     Sales = t2.Sales2 
    from temp1 t1 join 
     (select p_id, SUM(t2.Margin2) as margin2, SUM(t2.Revenue2) as revenue2, 
       SUM(t2.Sales2) as sales2 
      from tempcost t2 
      group by p_id 
     ) t2 
     on t1.P_Id = t2.P_Id; 
+0

感謝您的幫助:)。 – Shivam657

+0

銷售額= t2.Sales(不是分號) – Shivam657

1

如何將它移動到子查詢中?

Update temp1 t1 
    set t1.Margin = t2.Margin 
     ,t1.Revenue = t2.Revenue 
     ,t1.Sales = t2.Sales2 
    from t1 
    join (
     SELECT 
      SUM(Margin2) as Margin 
      ,SUM(Revenue2) as Revenue 
      ,SUM(Sales2) as Sales 
     FROM tempcost 
    ) t2 
    on t1.P_Id = t2.P_Id 
+0

您在子查詢中忘記了逗號。 – Shivam657

+0

感謝您的幫助,它的工作原理。 – Shivam657