I have a database table like this:
id date value minute
1 20100201 00:00:01.909 xxx 0
2 20100201 00:00:02.408 xxx 0
3 20100201 00:01:02.412 xxx 1
4 20100201 00:01:02.909 xxx 1
5 20100201 00:01:02.921 xxx 1
6 20100201 00:01:02.955 xxx 1
7 20100201 00:02:01.903 xxx 2
8 20100201 00:02:25.332 xxx 2
9 20100201 00:03:12.003 xxx 3
10 20100201 00:04:12.003 xxx 4
...
I want the results to be:
id date value1 minute
1 20100201 00:00:01.909 xxx 0
2 20100201 00:00:02.408 xxx 0
3 20100201 00:01:02.412 xxx 1
6 20100201 00:01:02.955 xxx 1
7 20100201 00:02:01.903 xxx 2
8 20100201 00:02:25.332 xxx 2
9 20100201 00:03:12.003 xxx 3
I want to query it and return the id with the first & last number for each minute and 1 record per minute if only 1 exists (so id 1,2,3,6,7,8,9 in the above).
I've tried using group by ordering by id ASC - group by minute but it seems to order after its grouped, so this doesn't work.
Anyone got any ideas? I can't believe it can't be done!
Try this query -
SELECT t1.* FROM test_table t1
JOIN (
SELECT MIN(id) min_id, MAX(id) max_id FROM test_table
GROUP BY TIME_TO_SEC(TIME(date)) DIV 60) t2
ON t1.id = t2.min_id OR t1.id = t2.max_id
If date
field is not a DATETIME or TIMESTAMP, then GROUP BY should be modified. Also, I advise you to group by exact minute (eg - group by year, day_of_year, minute_of_day).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.