Min()和分组的SQL查询

时间:2014-12-10 07:14:55

标签: mysql

我的表名是powerpro,包括以下数据

+-----------+-------------------+---------------+
| record_no |     date_time     | phase1_energy |
+-----------+-------------------+---------------+
|           |                   |               |
|         1 | 12/01/14 12:00 AM |           234 |
|         2 | 12/01/14 01:00 AM |           230 |
|         3 | 12/01/14 02:00 AM |           220 |
|         4 | 12/01/14 03:00 AM |           222 |
|         5 | 13/02/14 12:00 AM |           233 |
|         6 | 13/02/14 01:00 AM |           234 |
|         7 | 13/02/14 02:00 AM |           220 |
|         8 | 13/02/14 03:00 AM |           220 |
|         9 | 14/03/14 12:00 AM |           234 |
|        10 | 14/03/14 01:00 AM |           231 |
|        11 | 14/03/14 02:00 AM |           219 |
|        12 | 14/03/14 03:00 AM |           216 |
+-----------+-------------------+---------------+

我希望将phase1_energy余额(从每天最低读数扣除第二天的最低读数)恢复到现在的7天()

我试过了:

SELECT a1.* FROM powerpro a1
INNER JOIN
(
  select MIN(date_time) as min FROM powerpro
  GROUP BY date(date_time)
) a2

ON a1.date_time = a2.min 
WHERE date_time BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY date_time

但是每天只获得最低读数如下。

+-----------+-------------------+---------------+
| record_no |     date_time     | phase1_energy |
+-----------+-------------------+---------------+
|           |                   |               |
|         1 | 12/01/14 12:00 AM |           234 |
|         5 | 12/02/14 12:00 AM |           233 |
|         9 | 12/03/14 12:00 AM |           234 |
+-----------+-------------------+---------------+

任何人都可以帮助我吗?感谢

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望每个日期都需要最短时间(您设法获得),以及第二天的最短时间。

以下是你如何在第二天的最短时间内获得(编辑:增加两天的能量):

SELECT DATE(a1.date_time) AS `date`, a1.date_time AS this_day_min_read,  a1.phase1_energy AS this_day_energy,
a4.date_time AS next_day_min_read, a4.phase1_energy AS next_day_energy
FROM powerpro a1
JOIN (SELECT DATE(date_time) `date`, MIN(date_time) AS `min` 
        FROM powerpro
        GROUP BY DATE(date_time)
       ) a2 ON a1.date_time = a2.min 
JOIN (SELECT DATE(date_time) `date`, MIN(date_time) AS `min` 
        FROM powerpro
        GROUP BY DATE(date_time)
       ) a3 ON DATE(a1.date_time) = a3.date - INTERVAL 1 DAY 
JOIN powerpro a4
    ON a4.date_time = a3.min
WHERE date_time BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() 
ORDER BY date_time

希望这会有所帮助。