[英]**SQLAlchemy**:Get a count of one column where another column is distinct
這要死我了! 我確定這是我的 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 問題及其評論/答案,但不幸的是,我無法將解決方案翻譯成我的問題。
你真的很接近 - 基本上你需要告訴你的查詢要計算什么
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.