2011-12-02 114 views
1

我试图生成一个SQL查询来提取一个ID的平均montly powerusage(一年)。SQL查询提取按列分组的平均值

+----+------------+------------+ 
| 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我想要(平均十一月+平均十二月)/ 2 =(二分之一千七百五十+三分之一千六百五十○)/ 2 = 712.5

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

但是,这将得到我680.

我该如何做一个群体的平均水平?

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

+0

如果你的日期是十月和十二月,但不是十一月?总和除以3还是2? –

+0

你是否尝试过'通过身份证组'? –

+0

您的电力数据是每天存储的吗? –

回答

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 
+0

+1。很好的方式来实现这个问题。 –

+0

谢谢。我认为ajreal得到了与我早一分钟相同的答案 – Jaydee

0

试穿ID

GROUP BY id 

或日期为准适合添加组通过。

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 

警告:无论是上述的性能进行了优化。

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 */ 
+0

+1打我吧 – Jaydee

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 
+0

它被标记为'MySQL',而不是'SQL-Server' –

+0

PS。删除最后一组“年份”和年份选择器,如果你只是想要所有的时间每月平均值 –

+0

它应该是几乎相同的代码。我只是没有手上的mysql db来尝试内部选择语法 –