Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

sql - Group records by time

I have a table containing a datetime column and some misc other columns. The datetime column represents an event happening. It can either contains a time (event happened at that time) or NULL (event didn't happen)

I now want to count the number of records happening in specific intervals (15 minutes), but do not know how to do that.

example:

id | time                | foreign_key
1  | 2012-01-01 00:00:01 | 2
2  | 2012-01-01 00:02:01 | 4
3  | 2012-01-01 00:16:00 | 1
4  | 2012-01-01 00:17:00 | 9
5  | 2012-01-01 00:31:00 | 6

I now want to create a query that creates a result set similar to:

interval            | COUNT(id)
2012-01-01 00:00:00 | 2
2012-01-01 00:15:00 | 2
2012-01-01 00:30:00 | 1

Is this possible in SQL or can anyone advise what other tools I could use? (e.g. exporting the data to a spreadsheet program would not be a problem)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Give this a try:

select datetime((strftime('%s', time) / 900) * 900, 'unixepoch') interval,
       count(*) cnt
from t
group by interval
order by interval

Check the fiddle here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...