如何使用条件插入SQL Server表中每列的平均值

时间:2011-08-16 12:06:16

标签: sql-server-2005

我创建了一个包含动态列的临时表。这些列是主表中的值。

说,

Id |Name
1  |Prepaid
2  |Postpaid

所以临时表列将是

Id Prepaid Postpaid

在这种情况下,列是动态的。

考虑下面的临时表代码:

declare @temp as table (Id int, Prepaid float, postpaid float)

insert into @temp values(1,100,200)
insert into @temp values(1,10,500)
insert into @temp values(1,-100,-100)
insert into @temp values(1,10,200)
insert into @temp values(1,100,-100)
insert into @temp values(1,150,560)
insert into @temp values(1,90,200)

我需要插入一行,每列的平均值。

应使用符合条件的行计算平均值,即列不应包含值-100

我需要插入一个平均值的行,就像上面的值一样。

Id       PrepaidAvg      PostPaidAvg  
1     76.6666666666667  320

非常紧急。任何人都可以帮助我吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

很难确切地确定您期望的结果,但这是一次尝试:

SELECT 
  Id, 
  PrepaidAvg = AVG(CASE WHEN Prepaid > 0 THEN Prepaid ELSE NULL END),
  PostpaidAvg = AVG(CASE WHEN postpaid > 0 THEN postpaid ELSE NULL END)
FROM @temp
GROUP BY Id;

如果关闭,您可以更详细地说明:

;WITH prepaid AS
(
  SELECT Id, PrepaidAvg = AVG(Prepaid)
    FROM @temp WHERE Prepaid > 0
), postpaid AS
(
  SELECT Id, PostpaidAvg = AVG(postpaid)
    FROM @temp WHERE postpaid > 0
)
SELECT Id = COALESCE(prep.Id, postp.Id),
  prep.PrepaidAvg,
  postp.PostpaidAvg
FROM prepaid AS prep
FULL OUTER JOIN postpaid AS postp
ON prep.Id = postp.Id;

答案 1 :(得分:0)

使用此查询

insert into @temp 
select avg(Id), avg(Prepaid), avg(postpaid)
from @temp 
where Prepaid <> -100 and postpaid <> -100