获取按特定日期分类的列的平均值

时间:2015-02-14 18:29:18

标签: sql sqlite

我有以下格式的
DATETIME TEMPERATURE1 HUMIDITY1

其中记录(日期时间)的间隔为2小时 我希望得到每周的最低,平均和最高。 我可以想象在12个月内制作以下视图

SELECT 1 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-01%' UNION
SELECT 2 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-02%' UNION
SELECT 3 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-03%' UNION
SELECT 4 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-04%' UNION
SELECT 5 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-05%' UNION
SELECT 6 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-06%' UNION
SELECT 7 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-07%' UNION
SELECT 8 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-08%' UNION
SELECT 9 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-09%' UNION
SELECT 10 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-10%' UNION
SELECT 11 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-11%' UNION
SELECT 12 AS month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
  FROM TandRH WHERE DATE(dt) LIKE '2014-12%'

1。我怎么能这样做52周? 2. 12个月内是否有更智能的解决方案? 3.我也想制作一个新表并每周更新一次,但这会存储两次相同的数据。

谢谢

1 个答案:

答案 0 :(得分:1)

您有几周和几个月的问题。几个月我会回答这个问题。您想使用group by

SELECT month(date) as month, min(t1) AS mn, avg(t1) AS av, max(t1) AS mx
FROM TandRH 
WHERE year(date) = 2014
GROUP BY month(date);

您可以使用weekofyear()代替month()来执行类似的操作。