【问题标题】:sqlalchemy - How to group and counget last 12 month data from tablesqlalchemy - 如何从表中分组和计算最近 12 个月的数据
【发布时间】:2020-01-07 21:15:59
【问题描述】:

我有一个包含用户、类别和注册日期的表,我需要按月和类别获取过去 12 个月的用户组计数。

user    register_date   category
a   1/7/2020    1
b   2/8/2020    1
c   1/9/2020    1
d   2/10/2020   2
e   1/11/2020   2
f   2/12/2020   2
g   2/13/2020   3
h   1/14/2020   3
e   1/11/2020   1
f   2/12/2020   1
g   2/13/2020   2
h   1/14/2020   3
e   1/11/2020   3
f   2/12/2020   1

我尝试过这样的事情。我真的对代码感到困惑......

 @classmethod
def cont_user(cls):
    return cls.query(cls.user.count(), ).group_by(extract('year', cls.registerd_date),
         extract('month', cls.registered_date)).first(12)

这是我在 MS SQL 中实现它的方式 --> 但要求是使用 flask-sqlalchemy 进入 mysql(这只是为了提供有关要求的想法)

  SELECT count([UserName]) as user, DATENAME(month, [Registered_date]) + '-' +  CAST(YEAR([Registered_date]) AS nvarchar) as my, [category]

  FROM [database].[dbo].[user_table] group by [category], DATENAME(month, [Registered_date]) + '-' +  CAST(YEAR([Registered_date]) AS nvarchar)

我已经参考了以下链接,但未能按照我的要求进行转换...

Group by & count function in sqlalchemy

MySQL get quantities from last 12 months grouped by month

期待这样的输出。

count   month-year  category
10  Jan-19  1
15  Jan-19  2
20  Jan-19  3
12  Feb-19  1
14  Feb-19  2
19  Feb-19  3
9   Mar-19  1
19  Mar-19  2
24  Mar-19  3

【问题讨论】:

  • limit(12).all()代替first(12)

标签: python sqlalchemy flask-sqlalchemy


【解决方案1】:

利用sqlalchemy.func 创建本机SQL 函数表达式。 YEAR()func.yearCOUNTfunc.count,以此类推。

from sqlalchemy import func

cls.query(func.count(cls.user), cls.category)
    .group_by(func.year(cls.registered_date), func.month(cls.registered_date), cls.category)
    .limit(12).all()

【讨论】:

  • 添加上下文以防止投票和/或机器人删除答案。
  • 我收到错误 -> TypeError: 'BaseQuery' object is not callable
  • 我在这里缺少什么...?
【解决方案2】:

当我们使用类方法时,需要使用with_entities

感谢您的帮助....

经过一些实验,下面的代码对我有用。

添加了 _entities。还包括月份和年份以匹配顶部的输出。

from sqlalchemy import func

cls.query.with_entities(func.count(cls.user), cls.category, func.year(cls.registered_date), func.month(cls.registered_date))
    .group_by(func.year(cls.registered_date), func.month(cls.registered_date), cls.category)
    .limit(12).all()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2021-08-14
    • 1970-01-01
    • 2016-12-19
    相关资源
    最近更新 更多