繁体   English   中英

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

[英]Sql query to extract average grouped by a column

我正在尝试生成SQL查询以提取ID的平均每月使用量(一年)。

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

我如何对一个小组进行平均?

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

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

就像是

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

这应该为您提供每年和每个用户的每月平均值。 某些语法可能是特定于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

尝试在ID上添加分组

GROUP BY id

或日期,以适合的日期为准。

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

警告:以上两项均未针对性能进行优化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM