3

该任务是将日期时间值(使用 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 有按分钟分组的功能吗?

4

1 回答 1

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)
)
于 2012-07-01T10:48:44.007 回答