0

有一个我在 python 中创建的具有DATETIME字段的 sqlite db:

import sqlite3
con = sqlite3.connect('some.db',detect_types=sqlite3.PARSE_DECLTYPES)
with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE Table(...Date DATETIME...)")
    ...
    Date = datetime.datetime(<a format that resolves to the correct datetime object>)
    ...
    altogether = (..., Date, ...)
    cur.execute("INSERT INTO Table VALUES(...?...)", altogether)
    con.commit()

这会正确填充。后来我希望能够按日期时间查询这个数据库,并有一个功能来管理我的查询:

def query_db(path, query, args=(), one=False):
    connection  = sqlite3.connect(path)
    cur = connection.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

LOCAL_FOLDER = os.getcwd()
samplequery = "SELECT * FROM Table"
dbFile  = os.path.join(LOCAL_FOLDER, "some.db")
result = query_db(dbFile, samplequery)

以上将成功地产生一个result给我一切的Table.

但是,我如何构建一个查询,例如,给我过去 60 天内Table表中的some.db所有条目?Date

4

1 回答 1

1

You can do a query like this:

SELECT *
FROM Table
where date >= date('now', '-60 day');

EDIT:

Based on your actual query:

select <field1>, <field2>, count(1) as num
FROM Table
where date >= date('now', '-60 day');
group by <field1>, <field2>;

SELECT DISTINCT is unnecessary when you are using GROUP BY.

于 2013-07-22T02:30:06.720 回答