【问题标题】:How to convert this SQL query counting months and group by the month to sqlalchemy?如何将此 SQL 查询计数月份和按月分组转换为 sqlalchemy?
【发布时间】:2019-09-18 08:34:59
【问题描述】:

我正在尝试使用 sqlalchemy 和 postgresql 来获取数据。

我想使用这个查询

SELECT MONTH(date_field1), COUNT(*)
FROM table1
GROUP BY MONTH(date_field1)

这样我就可以得到月份列表及其计数,如下所示

month | count
1 | 3521
2 | 5222
3 | 1122
4 | 559
5 | 1664
6 | 3521
7 | 5222
8 | 1122
9 | 559
10 | 1664
11 | 559
12 | 1664

【问题讨论】:

  • 请发布您的表的 SQL 炼金术模型。也请检查this question,它与您的范围相同

标签: flask sqlalchemy flask-sqlalchemy


【解决方案1】:

Sqlalchemy 有 2 个不同的 modeORMcore

假设我有一个“创建”列是日期的表,您可以通过以下方式实现您想要的:

  • 使用ORM 模式:
from sqlalchemy import func

qry = session.query(func.month(Table.created), func.count(Table.created)).group_by(Table.created)
  • core:
from sqlalchemy import select 
from sqlalchemy import func

qry = select([func.month(tbl.c.created), func.count(tbl.c.created)]).group_by(tbl.c.created)

【讨论】:

  • 谢谢。这就是我想了解的关于 sqlalchemy 的内容。
猜你喜欢
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2010-09-16
  • 2021-10-03
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多