我有一系列带有特定时间戳的数据。我想查询一个月内每天的最接近度量值的数据,该值最接近6:00(t <6:00)。
我尝试了几种方法,但是没有一个能给我想要的确切结果。我不需要执行此查询:(
此刻我尝试执行的操作似乎无效。我尝试执行嵌套选择以获取有效时间列表,但我无法弄清其逻辑
SELECT Measure, Time FROM Table
WHERE EXTRACT(HOUR FROM Time) = 5
AND TIME IN(SELECT Time FROM Table)
最后,我尝试了EXTRACT(HOUR FROM Time) = 5 and EXTRACT(MINUTES FROM Time) = 59
,因为在我的特定情况下,它可以工作,但是我更愿意找到适当的解决方案。
比方说,我有很多非常规时间戳记的措施。我的查询应该给我的是30行(取决于月份),其行距接近时间戳是每天从后面到6:00。
感谢您的期待。
答案 0 :(得分:1)
这是解决问题的一种方法的可行示例。由于您最初没有指定数据库,所以我使用了MySQL。大多数SQL具有与日期和时间一起使用的类似功能,但有些可能需要稍作修改。
要创建测试数据库,请执行以下操作:
CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
USE `test`;
DROP TABLE if exists `samples`;
CREATE TABLE if not exists `samples` (
`id` int not null auto_increment,
`measure` float null,
`tstamp` timestamp,
primary key (`id`)
)
ENGINE = MyISAM;
INSERT `samples` (measure, tstamp) VALUES
(4.79, '2019-06-04 05:59:24'),
(6.80, '2019-06-04 05:59:46'),
(6.13, '2019-06-04 06:00:19'),
(8.18, '2019-06-04 06:01:22'),
(6.78, '2019-06-04 06:01:15'),
(3.79, '2019-06-03 08:00:00'),
(6.18, '2019-06-03 07:00:00'),
(4.78, '2019-06-03 06:00:00'),
(4.80, '2019-06-03 05:00:00'),
(4.13, '2019-06-03 04:00:00');
验证:
mysql> select * from samples;
+----+---------+---------------------+
| id | measure | tstamp |
+----+---------+---------------------+
| 1 | 4.79 | 2019-06-04 05:59:24 |
| 2 | 6.8 | 2019-06-04 05:59:46 |
| 3 | 6.13 | 2019-06-04 06:00:19 |
| 4 | 8.18 | 2019-06-04 06:01:22 |
| 5 | 6.78 | 2019-06-04 06:01:15 |
| 6 | 3.79 | 2019-06-03 08:00:00 |
| 7 | 6.18 | 2019-06-03 07:00:00 |
| 8 | 4.78 | 2019-06-03 06:00:00 |
| 9 | 4.8 | 2019-06-03 05:00:00 |
| 10 | 4.13 | 2019-06-03 04:00:00 |
+----+---------+---------------------+
10 rows in set (0.00 sec)
这里是一个查询,用于列出最接近6月3日06:00的样本数据:
USE test;
SELECT measure,
tstamp,
abs(time_to_sec (time(tstamp)) - time_to_sec('6:00:00')) AS delta
FROM samples
WHERE tstamp BETWEEN '2019-06-03' AND '2019-06-04'
ORDER BY delta
LIMIT 1;
相同查询,但选择6月4日:
SELECT measure,
tstamp,
abs(time_to_sec (time(tstamp)) - time_to_sec('6:00:00')) AS delta
FROM samples
WHERE tstamp BETWEEN '2019-06-04' AND '2019-06-05'
ORDER BY delta
LIMIT 1;
结果:
Database changed
+---------+---------------------+-------+
| measure | tstamp | delta |
+---------+---------------------+-------+
| 4.78 | 2019-06-03 06:00:00 | 0 |
+---------+---------------------+-------+
1 row in set (0.00 sec)
+---------+---------------------+-------+
| measure | tstamp | delta |
+---------+---------------------+-------+
| 6.8 | 2019-06-04 05:59:46 | 14 |
+---------+---------------------+-------+
1 row in set (0.00 sec)