单个SQL查询中的多个AVG

时间:2012-07-25 02:21:15

标签: sql average multiple-conditions

我已经搜索了添加多个AVG计算并找到了一些条目,但是我不得不加入另一个表格并且其示例很少。

我能找到的最接近答案是this 但它处理日期和没有联接

这是我的表格:

指标:

StandardScore             IndicatorID      NID    DID
0.033333                  7                1      1
0.907723                  9                1      1
0.574739                  26               1      1
0.917391                  21               1      1
.....

indexindicators:

IndexID                   IndicatorID
1                         7
1                         26
2                         21
3                         7
4                         9
4                         21
4                         7
5                         9
.......

我的目标是获得与NID / DID(指标)组合相关的每个IndexID(indexindicators)的平均值

检索单个值的查询将是

SELECT AVG(StandardScore) FROM `indicators` INNER JOIN indexindicators ON indicators.IndicatorId=indexindicators.IndicatorId WHERE nid=1 AND did=1 AND indexindicators.IndexId=1

最终将有6个(indexID)平均值,然后必须舍入然后*乘以100(我应该用PHP做那部分吗?)

这看起来像是一个简单的查询,但我似乎无法理解它。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

SELECT nid, did, indexid, 100.0 * AVG(StandardScore) 
    FROM 'indicators'
    INNER JOIN 'indexindicators'
      ON indicators.IndicatorId=indexindicators.IndicatorId 
group by nid, did, indexid