gpt4 book ai didi

python - SQLAlchemy 按分钟分组

转载 作者:可可西里 更新时间:2023-11-01 08:20:54 26 4
gpt4 key购买 nike

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

最佳答案

您可以通过 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)
)

关于python - SQLAlchemy 按分钟分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11278287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com