【问题标题】:sqlalchemy count unique parents by children month/yearsqlalchemy 按儿童月/年计算唯一父母
【发布时间】:2021-01-15 08:14:29
【问题描述】:

这对我来说有点难以解释,但我正在尝试创建一个查询来计算每月有多少唯一父母,具体取决于他们是否有出生日期在该月的孩子。所以我有一个有关系的父子模型。每个孩子都有一个出生日期和父母 ID,每个父母可以在其他孩子的同一个月内有多个孩子。如果父母在一月份有 10 个孩子,我只希望他们被计算一次。我可以像这样按月计算有多少孩子的生日:

children_query = db.query(func.count(Child.id).label('Children'),
                            func.extract('year', Child.birth_date),
                            func.extract('month', Child.birth_date))\
                            .group_by(func.extract('year', Child.birth_date),
                                    func.extract('month', Child.birth_date)).all()

但是,我在创建一个查询来计算每个月有多少父母有孩子的生日时遇到了麻烦。基本上我需要的结果需要显示 1 月有 10 个独特的父母有孩子,2 月 11 日,3 月 5 日,等等。

有没有办法删除重复的 parent_id 并按 parent_id 计数?

这是模型

class Parent(Base):
    id = Column(Integer, primary_key=True)
    children = relationship('Child', backref="parent")

class Child(Base):
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    birth_date = Column(DateTime, nullable=False)

【问题讨论】:

  • edit您的问题包括模型类(至少,相关的列和关系)
  • 我添加了简化模型

标签: python sqlalchemy


【解决方案1】:

我认为这个查询可以满足您的要求:

q = (session.query(sa.func.extract('YEAR', Child.birth_date).label('year'),
                   sa.func.extract('MONTH', Child.birth_date).label('month'),
                   sa.func.count(sa.func.distinct(Child.parent_id)))
            .group_by('year', 'month')
            .order_by('year', 'month'))

它生成这个 SQL(在 Postgres 上)

SELECT EXTRACT(YEAR FROM children.birth_date) AS year, 
       EXTRACT(MONTH FROM children.birth_date) AS month,
       count(distinct(children.parent_id)) AS count_1 
  FROM children 
  GROUP BY year, month 
  ORDER BY year, month

诀窍是使用COUNT(DISTINCT ...)

【讨论】:

  • 成功了,非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多