这是我的数据,每小时可能有几个Id
UKey - Primary Key
Epoch - epoch
Id - the transaction ID
查找数据库中所有日期的每小时的第一个交易ID 。
数据:
UKey Epoch Id
1 11:00:23 21-01-2016 xxx
2 11:01:33 21-01-2016 yyy
3 11:33:22 21-01-2016 zzz
4 12:03:41 21-01-2016 aaa
5 12:23:32 21-01-2016 bbb
6 12:34:43 21-01-2016 ccc
7 13:03:21 21-01-2016 ddd
8 13:04:22 21-01-2016 eee
9 14:00:01 21-01-2016 fff
10 16:00:01 23-01-2016 ggg
寻找这样的结果:
UKey Epoch Id
1 11:00:23 21-01-2016 xxx
4 12:03:41 21-01-2016 aaa
7 13:03:21 21-01-2016 ddd
9 14:00:01 21-01-2016 fff
10 16:00:01 23-01-2016 ggg
感谢您对此的投入,请确保此处的数据是一个示例,可能会有很多天和月,因此日期可能会有所不同
答案 0 :(得分:4)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(ukey INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,epoch DATETIME NOT NULL
,id CHAR(12)
);
INSERT INTO my_table (epoch,id) VALUES
('2016-01-21 11:00:23', 'xxx'),
('2016-01-21 11:01:33', 'yyy'),
('2016-01-21 11:33:22', 'zzz'),
('2016-01-21 12:03:41', 'aaa'),
('2016-01-21 12:23:32', 'bbb'),
('2016-01-21 12:34:43', 'ccc'),
('2016-01-21 13:03:21', 'ddd'),
('2016-01-21 13:04:22', 'eee'),
('2016-01-21 14:00:01', 'fff'),
('2016-01-23 16:00:01', 'ggg');
SELECT x.*
FROM my_table x
JOIN
( SELECT DATE_FORMAT(epoch,'%Y-%M-%D %h')dt,MIN(ukey) min_ukey
FROM my_table
GROUP BY dt
) y
ON y.dt = DATE_FORMAT(x.epoch,'%Y-%M-%D %h')
AND y.min_ukey = x.ukey;
+------+---------------------+------+
| ukey | epoch | id |
+------+---------------------+------+
| 7 | 2016-01-21 13:03:21 | ddd |
| 9 | 2016-01-21 14:00:01 | fff |
| 1 | 2016-01-21 11:00:23 | xxx |
| 4 | 2016-01-21 12:03:41 | aaa |
| 10 | 2016-01-23 16:00:01 | ggg |
+------+---------------------+------+