Sql查询提取按列分组的平均值

时间:2011-12-02 16:24:54

标签: mysql sql

我正在尝试生成一个SQL查询来提取ID的平均montly powerusage(一年)。

+----+------------+------------+
| id | powerusage |    date    |
+----+------------+------------+
|  1 |        750 | 2011-12-2  |
|  1 |       1000 | 2011-12-1  |
|  1 |       1500 | 2011-11-15 |
|  1 |        100 | 2011-11-13 |
|  1 |         50 | 2011-11-10 |
|  2 |        500 | 2011-11-15 |
|  2 |        200 | 2011-11-13 |
+----+------------+------------+

所以如果ID = 1我想要(平均11月+平均12月)/ 2 =(1750/2 + 1650/3)/ 2 = 712.5

select AVG(powerusage) as avgMontlyPowerUsage
from usagetable 
where id = 1 and YEAR(date) = 2011

但这会给我680。

如何对群组进行平均分析?

非常感谢所有答案!但我看到我的问题不正确。查看更新的问题

5 个答案:

答案 0 :(得分:3)

mysql> select avg(powerusage) 
from 
(select monthname(date), sum(powerusage) as powerusage 
from usagetable 
where id=1 and year(date)=2011
group by monthname(date)) as avg_usage;
+-----------------+
| avg(powerusage) |
+-----------------+
|       1700.0000 |
+-----------------+
select avg(total_powerusage) 
from 
(select monthname(date), sum(powerusage) as total_powerusage 
 from usagetable 
 where id=1 and year(date)=2011
 group by monthname(date)
) as avg_usage;

/* the use of subquery 
   is to return total of unique occurrences, 
   and sum powerusage of each occurrence,
   which mean, you just need to apply AVG into the subquery */

答案 1 :(得分:3)

这样的东西
select AVG(montlyPowerUsage) from (

SELECT MONTH(date) as mnth,sum(powerusage) as montlyPowerUsage
from usagetable 
where id = 1 and YEAR(date) = 2011 group by MONTH(date)

) t1

编辑问题

select AVG(montlyPowerUsage) from (

SELECT MONTH(date) as mnth,AVG(powerusage) as montlyPowerUsage
from usagetable 
where id = 1 and YEAR(date) = 2011 group by MONTH(date)

) t1

答案 2 :(得分:1)

这应该为您提供每年和用户的月平均值。一些语法可能是MS SQL特定的,但逻辑应该是好的。

SELECT id, AVG(usage), year FROM
(SELECT id, SUM(powerusage) as usage, YEAR(date) as Year, MONTH(date) as Month
  FROM usagetable 
  GROUP BY id, YEAR(date), MONTH(date)) as InnerTable
GROUP BY id, year

答案 3 :(得分:0)

尝试在ID上添加一个组

GROUP BY id

或日期,以适合者为准。

答案 4 :(得分:0)

SELECT SUM(powerusage) / (MONTH(MAX(`date`)) - MONTH(MIN(`date`)) + 1)
           AS avgMontlyPowerUsage
FROM usagetable 
WHERE id = 1 
  AND YEAR(`date`) = 2011

或(取决于数据稀疏时的需要):

SELECT SUM(powerusage) / COUNT( DISTINCT MONTH(`date`) )
           AS avgMontlyPowerUsage
FROM usagetable 
WHERE id = 1 
  AND YEAR(`date`) = 2011

警告:上述两种方法均未针对性能进行优化。