SQLAlchemy按间隔30分钟分组

我在Python和SQL Alchemy领域还很陌生,对于我要执行的查询有疑问。

更具体地说,我有此数据列表。每5分钟包含一些措施。 我想做的是基于30分钟的时间戳分组,所以在以下情况下:

  • 00:15:00 + 00-> 00:00:00 + 00
  • 00:20:00 + 00-> 00:00:00 + 00
  • 00:30:00 + 00-> 00:30:00 + 00
  • 00:35:00 + 00-> 00:30:00 + 00

,然后汇总该值上的数据。

现在我有以下代码:

base_query = (
        db.query(
            MyTable.timestamp,func.max(MyTable.dual).label("max"),func.min(MyTable.dual).label("min"),func.avg(MyTable.dual).label("avg"),func.count(MyTable.id).label("count"),)
        .join(Simulation,Simulation.id == MyTable.simulation_id)
        .filter(
            and_(MyTable.dual > 0,Simulation.scenario_id == scenario_id)
        )
        .group_by(MyTable.timestamp)
        .order_by(MyTable.timestamp)
    )
timestamp                   count   avg
"2020-01-13 00:00:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:05:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:10:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:15:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:20:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:25:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:30:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:35:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:40:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:45:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:50:00+00"    "10"    "6454.70683325249"
"2020-01-13 00:55:00+00"    "10"    "6454.70683325249"
"2020-01-13 01:00:00+00"    "10"    "6454.70683325249"
"2020-01-13 01:05:00+00"    "10"    "6454.70683325249"
"2020-01-13 01:10:00+00"    "10"    "6454.70683325249"
"2020-01-13 01:15:00+00"    "10"    "6454.70683325249"
xlccy 回答:SQLAlchemy按间隔30分钟分组

首先,我们必须弄清楚如何在sql中做到这一点。间隔半小时 应该不太困难:

SELECT total_transaction,COUNT(*)
FROM (SELECT customer_no,COUNT(*) AS total_transaction
      FROM [bi-dwhdev-01:source.daily_order]
      WHERE DATE(order_time) >=  '2018-04-01' AND DATE(order_time) <=  '2018-04-10'
      GROUP BY customer_no
     ) c
GROUP BY total_transaction
ORDER BY total_transaction DESC;

您可能希望将其转换回日期时间,但恐怕并非如此 足够便携。在mysql中,您可以使用from_unixtime,但如果获得 unix时间戳作为查询的结果,您可以轻松地将其转换为 python中任何您想要的东西。

第二,如何在sqlalchemy中做到这一点。看起来很漂亮 简单:

select 1800*(floor(unix_timestamp(timestamp)/1800))
本文链接:https://www.f2er.com/3151091.html

大家都在问