2011-12-02 120 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來嘗試內部選擇語法 –