【问题标题】:how to get certain items from database [closed]如何从数据库中获取某些项目[关闭]
【发布时间】:2013-11-28 18:15:50
【问题描述】:

我在数据库中有以毫秒为单位的时间戳的项目

我想从中取出以下物品:

数据库中的项目中每个月的最后一项可用

要实现这一点,我的查询会是什么样子?

【问题讨论】:

  • 是什么样的数据库?
  • 你能展示一些你正在使用/尝试的查询吗?它将帮助我们回答您的问题。
  • select * from mytable where ?我不知道在这里写什么,这就是我问的原因,我需要每个月的最新项目,比如说我在数据库中有 100 个项目,从 1 月到 12 月分布,时间戳以毫秒为单位,我想要最新的每个月的项目

标签: sql sqlite


【解决方案1】:

如果我明白你想要什么,这就是它的要点。根据需要将列添加到选择中。

"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 随机日期选择技术。

【讨论】:

  • strftime 不处理毫秒时间戳。
猜你喜欢
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 2023-02-09
相关资源
最近更新 更多