使用JOIN - SQL Server在同一个表中使用平均值更新列

时间:2016-11-10 05:44:15

标签: sql sql-server join aggregate-functions average

我有下表

[Table_01]
ID  |   Name    |   Profit  |   AvgProfit
------------------------------------------
1   |   Donald  |   1001    |   
2   |   Hillary |   101     |   
3   |   Barack  |   11      |   
4   |   Bernie  |   1       |   
1   |   Donald  |   1002    |   
2   |   Hillary |   102     |   
3   |   Barack  |   12      |   
4   |   Bernie  |   2       |   
1   |   Donald  |   1003    |   
2   |   Hillary |   103     |   
3   |   Barack  |   13      |   
4   |   Bernie  |   3       |   

我需要为每个人添加平均利润值。

UPDATE后的结果应为:

[Table_01]
ID  |   Name    |   Profit  |   AvgProfit
------------------------------------------
1   |   Donald  |   1001    |   1002
2   |   Hillary |   101     |   102
3   |   Barack  |   11      |   12
4   |   Bernie  |   1       |   1
1   |   Donald  |   1002    |   1002
2   |   Hillary |   102     |   102
3   |   Barack  |   12      |   12
4   |   Bernie  |   2       |   1
1   |   Donald  |   1003    |   1002
2   |   Hillary |   103     |   102
3   |   Barack  |   13      |   12
4   |   Bernie  |   3       |   1

我使用以下方法获得平均值:

SELECT z1.*, AVG(Profit) OVER(PARTITION BY Name) AVERAGE
    FROM Table_01 z1
    order by Name

对于更新,我尝试了多个JOIN子句但没有成功。 我收到各种错误:在JOIN中使用AGGREGATE和无效的对象名称。

我认为这个适用于Oracle。

UPDATE Table_01 z1 
SET z1.AvgSecs = (SELECT AVG(Profit) 
                 FROM Table_01
                 WHERE Name = z1.Name)

Microsoft SQL Server 2014中使用的语法是什么?

问题2

我有另一张表需要更新

[Table_02]
Name    |   AvgProfit                   Name    |   AvgProfit
---------------------   UPDATE -->      ---------------------
Donald  |                               Donald  |   1002
Hillary |                               Hillary |   102
Barack  |                               Barack  |   12
Bernie  |                               Bernie  |   1

我想知道这是否有效:

UPDATE t2
SET t2.AvgProfit = t1.AvgProfit
FROM Table_02 t2
    join Table_01 t1 
    ON   t1.Name = t2.Name 

"名称"是唯一值

非常感谢所有人。

2 个答案:

答案 0 :(得分:3)

您可以使用CTE进行首次更新:

;WITH CTE AS
(
    SELECT Id, AVG(Profit) OVER (PARTITION BY Name) As AvgProfit
    FROM Table_01
)

UPDATE T1
SET AvgProfit = CTE.AvgProfit
FROM Table_01 T1 
INNER JOIN CTE ON(T1.Id = CTE.Id)

至于你的第二个问题 - 答案是肯定的。

答案 1 :(得分:1)

问题1:

 UPDATE Table_01 SET AvgProfit = _AvgProfit FROM
 (SELECT ID , AVG(Profit) _AvgProfit FROM Table_01 GROUP BY ID )
 A WHERE A.ID = Table_01.ID

问题2:

UPDATE Table_02 SET Table_02.AvgProfit = t1.AvgProfit 
FROM Table_01 t1 WHERE t1.Name = Table_02.Name