平均有条件

时间:2017-05-04 15:14:02

标签: sql sql-server-2008

我试图找出如何计算变量的精确平均值。 目前我有这个问题:(简化):

select ID , Group_ID, Chargeability,Job_No_, Group_Charg FROM Data1


ID      Group ID        Chargeability       Job No_     Group Chargeability
1             a             90                c1                 88.11
1             a             90                c2                 88.11
1             a             90                c3                 88.11
1             a             90                c4                 88.11
2             a             85.6              c8                 88.11
2             a             85.6              c17                88.11
2             a             85.6              c6                 88.11

计算的平均值不是实际值。 Chargability是针对每个ID固定的,因此平均值不应考虑每个ID的行数,因为它只是值的替代,因为我们每个ID都有多个job_No。

我希望Group_chargeability =(90 + 85.6)/ 2而不是目前正在做的(90 * 4)+(85.6 * 3)/ 7。

查询由几个子查询组成,其中一些也调用函数。这就是为什么我不能用group by来解决我的问题。

3 个答案:

答案 0 :(得分:2)

AVG功能与SUB QUERY

一起使用
SELECT d.ID, d.Group_ID, d.Chargeability, d.Job_No_, 
AVG(SELECT MIN(sub.Chargeability) 
 FROM Data1 sub
 WHERE sub.id = d.id AND sub.Job_No_ = d.Job_No_
 GROUP BY sub.ID) AS GROUP_Chargeability
FROM Data1

答案 1 :(得分:1)

您可以尝试使用这样的连接子查询:

SELECT d.ID, d.GROUP_ID, d.CHARGEABILITY, d.JOB_NO_, d2.charges 
FROM Data1 d LEFT JOIN 
(SELECT DISTINCT ID, GROUP_ID, AVG(CHARGEABILITY) AS CHARGES FROM Data1) d2 
    ON d2.ID = d.ID AND d2.GROUP_ID = d.GROUP_ID

答案 2 :(得分:1)

计算整体平均可充电性:

select avg(Chargeability) as avgChargeability
from (select id, avg(Chargeability) as Chargeability
      from t
      group by id
     ) id;

您可以使用join或子查询将此值添加到每一行。