我有一个名为'measurement'的表,其中包含id(pri_key),dt(timestamp)和用作列。 最小或最大使用可以多次发生。我想选择昨天使用最小值和最大值的第一条记录。
到目前为止我所拥有的:
SELECT dt, usage FROM measurement as a,
(SELECT MIN(usage) as mini, MAX(usage) as maxi FROM measurement) as m
WHERE m.mini = a.usage OR m.maxi = a.usage AND
a.dt >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE(a.dt) < DATE(NOW());
这给了我:
+---------------------+-----------------+
| dt | usage |
+---------------------+-----------------+
| 2017-01-10 01:11:01 | 6 |
| 2017-01-10 01:55:01 | 6 |
| 2017-01-10 02:19:01 | 6 |
| 2017-01-10 03:11:02 | 6 |
| 2017-01-10 04:57:01 | 6 |
| 2017-01-11 08:22:02 | 6 |
| 2017-01-11 13:42:02 | 6 |
| 2017-01-11 17:52:01 | 2609 |
| 2017-01-11 23:06:01 | 6 |
| 2017-01-12 03:29:02 | 6 |
| 2017-01-12 04:17:02 | 6 |
| 2017-01-12 05:39:01 | 6 |
+---------------------+-----------------+
昨天当我忙于这个项目时,它至少会给我前一天的所有记录。现在它只是给我所有记录的最低值和最高值。无论如何,我试图通过使用:
在第一次发生值'6'并且发生值'2609'时进行过滤SELECT dt, usage FROM measurement as b,
(SELECT MIN(dt) as first, usage as us FROM measurement) as a,
(SELECT MIN(usage) as mini, MAX(usage) as maxi FROM measurement) as m
where m.mini = a.us or m.maxi = a.us and
a.first >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE(a.first) < DATE(NOW());
然而,这给了我一个空集。我在寻找:
| 2017-01-11 08:22:02 | 6 |
| 2017-01-11 17:52:01 | 2609 |
答案 0 :(得分:2)
这可能不是最好的解决方案,但是一个选项是使用子查询来限制从昨天结合排序和LIMIT 1
获得最小/最大使用量的记录,以获得每种情况下的最早记录。
对于昨天最早的最低使用量:
SELECT a.dt,
a.usage
FROM measurement a
WHERE a.dt BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE(NOW()) AND
a.usage = (SELECT MIN(usage) FROM measurment
WHERE dt BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE(NOW()))
ORDER BY a.dt
LIMIT 1
从昨天起最早使用的最长时间:
SELECT a.dt,
a.usage
FROM measurement a
WHERE a.dt BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE(NOW()) AND
a.usage = (SELECT MAX(usage) FROM measurment
WHERE dt BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND DATE(NOW()))
ORDER BY a.dt
LIMIT 1