SQLAlchemy分组

时间:2012-06-30 22:57:15

标签: python mysql sql orm sqlalchemy

该任务是将每个分钟的日期时间值(使用SQLAlchemy)分组(按分钟分组)。

我有一个自定义SQL查询:

SELECT COUNT(*) AS point_value, MAX(time) as time
  FROM `Downloads` 
  LEFT JOIN Mirror ON Downloads.mirror = Mirror.id 
 WHERE Mirror.domain_name = 'localhost.local' 
   AND `time` BETWEEN '2012-06-30 00:29:00' AND '2012-07-01 00:29:00'
 GROUP BY DAYOFYEAR( time ) , ( 60 * HOUR( time ) + MINUTE(time ))
 ORDER BY time ASC

它很棒,但现在我已经在SQLAlchemy中完成了。这就是我现在所拥有的(按年份分组只是一个例子):

rows = (DBSession.query(func.count(Download.id), func.max(Download.time)).
    filter(Download.time >= fromInterval).
    filter(Download.time <= untilInterval).
    join(Mirror,Download.mirror==Mirror.id).
    group_by(func.year(Download.time)).
    order_by(Download.time)
)

它给了我这个SQL:

SELECT count("Downloads".id) AS count_1, max("Downloads".time) AS max_1 
FROM "Downloads" JOIN "Mirror" ON "Downloads".mirror = "Mirror".id 
WHERE "Downloads".time >= :time_1 AND "Downloads".time <= :time_2 
GROUP BY year("Downloads".time) 
ORDER BY "Downloads".time

正如您所看到的,它只缺少正确的分组:

GROUP BY DAYOFYEAR( time ) , ( 60 * HOUR( time ) + MINUTE(time ))

SQLAlchemy是否有一些按分钟分组的功能?

1 个答案:

答案 0 :(得分:3)

您可以通过Functions使用SA中的任何SQL端功能,您已经在YEAR部分使用了该功能。我认为在你的情况下你只需要添加(未测试):

from sqlalchemy.sql import func
...
# add another group_by to your existing query:
rows = ...
group_by(func.year(Download.time), 
         60 * func.HOUR(Download.time) + func.MINUTE(Download.time)
)