组合时如何获得平均值相同的平均值?

时间:2016-06-03 06:54:50

标签: sql sql-server

我在表格中有3列,如FreqHeader,Frequency和Avgwaittime。当我获得平均Avgwaittime时,它是26.66。如果我通过FreqHeader得到平均Avgwaittime组,则频率给出25.15。

如果我将FreqHeader,Frequency?

分组,我怎么能得到26.66

这是我的表:

FreqHeader  Frequency   Avgwaittime
Week         19         6.73
Week         19         96.62
Week         20         15.22
Week         20         20.84
Week         20         41.77
Week         21         9.01
Week         21         25.42
Week         21         31.20
Week         22         36.01
Week         22         17.20
Week         22         17.05
Week         23         2.85

以上Avgwaittime的平均值为26.66

这是我的查询

SELECT FreqHeader, Frequency, CAST(AVG(Avgwaittime) as decimal(10,2)) Avgwaittime
from #temp
GROUP BY FreqHeader, Frequency

FreqHeader  Frequency   Avgwaittime
Week          19        51.68
Week          20        25.94
Week          21        21.88
Week          22        23.42
Week          23        2.85

当我计算这5条记录的平均值时应该是26.66。但这里是25.15

2 个答案:

答案 0 :(得分:0)

您必须使用子查询:

SELECT FreqHeader, Frequency, 
       CAST(AVG(Avgwaittime) as decimal(10,2)) Avgwaittime,
       (SELECT CAST(AVG(Avgwaittime) as decimal(10,2))  FROM mytable) AS AvgwaittimeOverall
from mytable
GROUP BY FreqHeader, Frequency

答案 1 :(得分:0)

以下查询将显示所需的输出: -

SELECT FreqHeader, Frequency, 
(select CAST(AVG(COALESCE(Avgwaittime,0)) as decimal(10,2)) from table_name) Avgwaittime
from table_name
GROUP BY FreqHeader, Frequency

输出: -

  FreqHeader    Frequency   Avgwaittime
    Week           19         26.66
    Week           20         26.66
    Week           21         26.66
    Week           22         26.66
    Week           23         26.66