我的数据库中的项目的时间戳以毫秒为单位
我想从中获取以下项目:
db中项目中每个月的最后一项
我的查询会是什么样的?
答案 0 :(得分:0)
如果我明白你想要什么,这就是它的要点。根据需要在选择中添加列。
"SELECT STRFTIME('%m', time) AS month, max(time) FROM test GROUP BY month"
自包含python脚本演示:
from datetime import date
import sqlite3
import random
with open("./test", "w") as f:
pass
conn = sqlite3.connect("test")
cursor = conn.cursor()
table_sql = "CREATE TABLE test (time TIMESTAMP)"
cursor.execute(table_sql)
conn.commit()
insert_sql = "INSERT INTO test VALUES(?)"
for x in range(100):
start_date = date.today().replace(day=1, month=1).toordinal()
end_date = date.today().toordinal()
random_day = date.fromordinal(random.randint(start_date, end_date))
cursor.execute(insert_sql, (str(random_day),))
conn.commit()
query = "SELECT STRFTIME('%m', time) AS month, MAX(time) FROM test GROUP BY month"
cursor.execute(query)
print(cursor.fetchall())
信用:Python select random date in current year用于随机日期选择技术。