SQLite group by/count hours, days, weeks, year

徘徊边缘 提交于 2020-01-03 01:47:29

问题


Assume that we have a simple Android application that has only one button.
Click on that button record the date and time of that click (in sqlite).
I wondering what is the best format for that records keep a long or a string of that date-time.
The purpose is to make reports that show:
1. sum of clicks that made for chosen day grouped by hours.
2. sum of clicks that made for chosen week grouped by days.
3. sum of clicks that made for chosen month grouped by weeks.
4. sum of clicks that made for chosen year grouped by month.

How to create such database and how do I do such queries?


回答1:


I'd vote for using Unix timestamps (number of seconds since the "epoch"), given that they're convenient for range calculation and understood by most robust date-time libraries.

SQLite provides a few helper functions for working with Unix timestamps. The most useful one here is going to be strftime.

You can insert the current Unix timestamp by using strftime('%s', 'now') in your INSERT.

Later, if you know a particular time range you're interested in, you can calculate the minimum and maximum timestamps for that range and select rows between them:

SELECT * FROM data 
WHERE timestamp >= strftime('%s', '2012-12-25 00:00:00') 
AND timestamp < strftime('%s', '2012-12-25 01:00:00');

Or, supposing you want to count a year's requests by month:

SELECT strftime('%m', timestamp), count(*) FROM Data
WHERE timestamp >= strftime('%s', '2012-01-01 00:00:00') 
AND timestamp < strftime('%s', '2013-01-01 00:00:00') 
GROUP BY strftime('%m', timestamp);

Through clever use of the format options strftime provides, you can probably work out most of those queries pretty quickly.



来源:https://stackoverflow.com/questions/17821136/sqlite-group-by-count-hours-days-weeks-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!