来自其他表中更新的一个表的聚合值

时间:2014-02-14 05:43:39

标签: sql sql-server sql-server-2008

我想使用Update子句将聚合值从一个表插入到其他表中。这就是我所做的。

SELECT Sum(1.0 * volume * speed) / Sum(volume) AS aggregated_speed 
FROM   traffic_data_replica 
GROUP  BY date, 
          id 
ORDER  BY date; 

我想在其他表中更新此值。这就是我尝试过的。

UPDATE traffic_data_aggregated_lanes 
SET    traffic_data_aggregated_lanes.aggregated_speed = (SELECT 
              Sum(1.0 * volume * 
                  speed) / Sum(volume) AS aggregated_speed 
                                                         FROM 
       traffic_data_replica 
                                                         GROUP  BY date, 
                                                                   id 
                                                         ORDER  BY date); 

请帮助

2 个答案:

答案 0 :(得分:0)

关系尚不清楚。 有些

Merge traffic_data_aggregated_lanes a
using (select id, sum(1.0*volume*speed)/sum(volume) as aggregated_speed from  
traffic_data_replica group by date,id) b
on a.id=b.id
when matched then
update   set a.aggregated_speed= b.aggregated_speed

答案 1 :(得分:0)

我们可以使用CTE,我也不确定数据。 所以我给你假设结果

WITH CTE AS (
select t.Id,sum(1.0*volume*speed)/sum(volume) as aggregated_speed from  traffic_data_replica t 
group by date,id order by date
)
Select * FROM CTE
update traffic_data_aggregated_lanes    set traffic_data_aggregated_lanes.aggregated_sp= t.aggregated_speed From traffic_data_replica t
INNER JOIN CTE c ON C.Id = t.Id