【问题标题】:**SQLAlchemy**:Get a count of one column where another column is distinct**SQLAlchemy**:获取另一列不同的一列的计数
【发布时间】:2020-03-30 18:37:35
【问题描述】:

这可要了我的命!我确信这是我的 SQL 知识上的一个差距,但我在解决这个问题时遇到了很大的麻烦。 我需要统计每个国家的所有订单。关键是订单需要有一个唯一的 user_id 才能在计数中只包括唯一的客户。 这是我目前所拥有的,它返回一个总计数,包括来自同一 user_id 的订单。

country_col = model.Order.__table__.c.shipping_country_code
country_q = model.Session.query(country_col,
                                    func.count('*'))\
        join(model.Order.cart).\
        join(model.Cart.items).\
        join(model.CartItem.product).\
        filter(model.Product.project_id == project.id).\
        group_by(country_col).\
        order_by(func.count('*').desc())

country_q.all()

如果这似乎是重复的,我很抱歉。我已经阅读了所有 StackOverflow 问题及其 cmets/answers,但很遗憾,我无法将解决方案转化为我的问题。

【问题讨论】:

    标签: python mysql sql database sqlalchemy


    【解决方案1】:

    你真的很接近 - 基本上你需要告诉你的查询要计算什么

    country_col = model.Order.__table__.c.shipping_country_code
    country_q = model.Session.query(country_col,
                                    #here's where you need to indicate the value
                                    func.count(order_id.distinct()))\
        join(model.Order.cart).\
        join(model.Cart.items).\
        join(model.CartItem.product).\
        filter(model.Product.project_id == project.id).\
        group_by(country_col).\
        order_by(func.count(order_id.distinct()).desc())
    
    country_q.all()
    

    参考:https://stackoverflow.com/a/22275619/7853322

    【讨论】:

    • 哇哇哇!太感谢了!我必须将 user_id 添加到查询 country_q = model.Session.query(country_col, model.Order.user_id, func.count(order_id.distinct()))\ 但它工作得很好!非常感谢你,你是一个救生员!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多