日期:2014-05-18 浏览次数:20543 次
UPDATE a SET [数值]=d.[平均数值] from (select c.[主键],c.[平均数值] from (select a.[主键], avg(b.数值)[平均数值] from B left join A on a.[主键]=b.A表主键 group by a.[主键])c where a.[主键]=c.[主键])d
------解决方案--------------------
DECLARE @A TABLE(id INT ,VALUE INT) INSERT INTO @A SELECT 1,NULL DECLARE @B TABLE(id INT,A_id INT,method VARCHAR(10),VALUE INT ) INSERT INTO @B SELECT 999, 1, 'AAA', 122 UNION ALL SELECT 1000,1, 'BBB', 124 --1, SELECT [@A].id,AVG([@B].VALUE) AS avg_value FROM @A LEFT OUTER JOIN @B ON [@A].id = [@B].A_id GROUP BY [@A].id /* id avg_value ----------- ----------- 1 123 */ --2 UPDATE @A SET VALUE=t.avg_value FROM ( SELECT [@A].id,AVG([@B].VALUE) AS avg_value FROM @A LEFT OUTER JOIN @B ON [@A].id = [@B].A_id GROUP BY [@A].id ) AS t WHERE [@A].id=t.id SELECT * FROM @A /* id VALUE ----------- ----------- 1 123 */
------解决方案--------------------
UPDATE a SET [数值]= case when d.[平均数值] is not null then d.[平均数值] else a.[数值] end from (select c.[主键],c.[平均数值] from (select *, avg(b.数值)[平均数值] from B left join A on a.主键=b.A表主键 group by a.主键)c where a.主键=c.主键)d