2008-10-19 96 views

回答

0

我不知道SQLAlchemy,所以我可能会脱离目标。不过,我认为,所有你需要的是:

SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*) 
    FROM logs 
    GROUP BY date_formatter(datetime_field, "format-specification") 
    ORDER BY 1; 

OK,也许你并不需要ORDER BY,也许这将是更好地重新指定日期表达式。有可能有替代品,如:

SELECT dt_field, COUNT(*) 
    FROM (SELECT date_formatter(datetime_field, "format-specification") AS dt_field 
       FROM logs) AS necessary 
    GROUP BY dt_field 
    ORDER BY dt_field; 

等等等等。基本上,你格式化日期时间字段,然后继续对格式化的值进行分组等。

1

当您只是通过未格式化的日期时间列进行分组时,计数是否会产生相同的结果?如果是这样,你可以运行查询,然后使用Python日期的strftime()方法。即

query = select([logs.c.datetime, func.count(logs.c.datetime)]).group_by(logs.c.datetime) 
results = session.execute(query).fetchall() 
results = [(t[0].strftime("..."), t[1]) for t in results] 
4

我不知道一般的SQLAlchemy答案。大多数数据库通常通过函数支持某种形式的日期格式。 SQLAlchemy支持通过sqlalchemy.sql.func调用函数。因此,例如,使用的SQLAlchemy在Postgres的后端,和一张桌子MY_TABLE(富VARCHAR(30),当时间戳)我可能会按日期截断到一个月做类似

my_table = metadata.tables['my_table'] 
foo = my_table.c['foo'] 
the_date = func.date_trunc('month', my_table.c['when']) 
stmt = select(foo, the_date).group_by(the_date) 
engine.execute(stmt) 

到组。但请记住,在该示例中,date_trunc()是Postgres日期时间函数。其他数据库将会不同。你没有提到underlyig数据库。如果有一种数据库独立的方式来做到这一点,我从来没有找到一个。在我的情况下,我运行生产和测试aginst Postgres和单元测试aginst SQLite,并采取在我的单元测试中使用SQLite用户定义函数来模拟Postgress日期时间函数。

+0

正是我需要..现在到SQLite手册找到截断功能!我认为这是``STRFTIME('%Y-%m',当)``在我的情况下。 – 2012-03-26 14:19:56