2017-01-10 71 views
4

我想根据以下计算来计算加权平均数。在SQL Server中计算加权平均数

我有一个数据集,看起来是这样的:

item |  Date Sent  |  Date Received 
1 |  2 Feb 10am |  3 Feb 10am 
1 |  6 Feb 11am |  6 Feb 12pm 
2 |  2 Feb 10am |  3 Feb 10am 
2 |  6 Feb 11am |  6 Feb 12pm 

然后我需要计算基础上的时间差平均四舍五入意思是:

Time Diff | Count | 
    1  | 2 | 
    12  | 2 | 

所以在这种情况下,它会是:

1 * 2 + 12 * 2/(12 + 1) 

我已经编写了SQL查询来计算聚合表:

select 
    floor(datediff(hh, dateSent, dateReceived)) as hrs, 
    count(item) as freq 
from 
    table 
group by 
    floor(datediff(hh, dateSent, dateReceived)) 
having 
    floor(datediff(hh, dateSent, dateReceived)) < 100 
order by 
    floor(datediff(hh, dateSent, dateReceived)) asc; 

我应该做一个子查询吗?我不熟练,我尝试过,但不断收到语法错误。

有人可以帮助我得到SQL查询来获得加权平均值吗?

+0

我的猜测是你真正想要组通过这样的方式ID: 'SELECT item,hrs = AVG(DATEDIFF(HOUR,dateSent,dateReceived)),freq = COUNT(*)FROM myTable GROUP BY项目HAVING AVG(DATEDIFF(HOUR,dateSent,dateReceived))<100 ORDER BY 2;'像那样? – ZLK

+0

我实际上想要得到加权平均数,我认为这将是子查询的一部分,但我没有设法完成。你为什么要订购2? –

+0

我不确定你的意思是“加权平均”。它是如何“加权”的?另外,'2号'顺序只是懒惰的短语,说“按第二列排序”。 – ZLK

回答

4

如果你所说的“加权平均”的意思是平均的所有时间的差异,那么下面可能会有所帮助:

select AVG(a.hrs) 
from 
(
    select floor(datediff(hh,dateSent,dateReceived)) as hrs, 
    count(item) as freq from table 
     group by floor(datediff(hh,dateSent,dateReceived)) 
      having floor(datediff(hh,dateSent,dateReceived)) <100 
--    order by floor(datediff(hh,dateSent,dateReceived)) asc 
) a 
+0

是的,这非常接近谢谢!我不知道你可以做到这一点。我的最终结果只是选择和(a.hrs * a.freq)/ sum(a.freq)而不是AVG(a.hrs) –