如何使func.sum和group_by使用sqlalchemy输出行的总和并合并重复的行

时间:2019-05-10 07:31:22

标签: python sqlalchemy flask-sqlalchemy

我想生成一个表,该表将在给定时间内出售的图书数量与该不同图书的已付款总额相加。我需要它来显示已售书的报告。

我的子查询是:

bp = db.session.query(CustomerPurchase.book_category_id, 
func.sum(CustomerPurchase.amount).label('amount'),
func.sum(CustomerPurchase.total_price).label('total_price'))\
.filter(CustomerPurchase.created_on >= start_date)\
.filter(CustomerPurchase.created_on <= end_date)\
.group_by(CustomerPurchase.book_category_id).subquery()

组合查询和子查询:

cp = CustomerPurchase.query\
.join(bp, bp.c.category_id == CustomerPurchase.category_id)\
.distinct(bp.c.category_id)\
.order_by(bp.c.category_id)

我的CustomerPurchase表如下所示,而查询的输出则相同:

id | book_category_id | book_title | amount | total_price |
---+------------------+------------+--------+-------------+
 1 |        1         | Book A     |   10   |    35.00    |
 2 |        1         | Book A     |   20   |    70.00    |
 3 |        2         | Book B     |   40   |    45.00    |

查询运行后所需的输出应如下所示:

id | book_category_id | book_title | amount | total_price |
---+------------------+------------+--------+-------------+
 1 |        1         | Book A     |   30   |  105.00     |
 2 |        2         | Book B     |   40   |   45.00     |

上面的查询显示了从CustomerPurchase表中出售给客户的所有图书,但没有SUM amounttotal_price,也没有合并重复的图书

我看到了很多例子,但没有一个对我有用。任何帮助是极大的赞赏!预先感谢!

1 个答案:

答案 0 :(得分:0)

因此,经过大量研究和试验,我提出了一个解决了我问题的查询。基本上,我在sqlalchemy中使用了add_column属性,该属性为我提供了要显示在报告中的确切行。

bp = db.session.query(CustomerPurchase.book_store_category_id,
func.sum(CustomerPurchase.quantity).label('quantity'),
func.sum(CustomerPurchase.total_price).label('total'))\
.filter(CustomerPurchase.created_on >= start_date)\
.filter(CustomerPurchase.created_on <= end_date)

bp = bp.add_column(BookStore.book_amount)\
.filter(BookStore.category_id == CustomerPurchase.book_store_category_id)

bp = bp.add_columns(Category.category_name, Category.total_stock_amount)\
.filter(Category.id == CustomerPurchase.book_store_category_id)

bp = bp.add_column(Category.unit_cost)\
.filter(Category.id == CustomerPurchase.book_store_category_id)

bp = bp.add_column(Book.stock_amount)\
.filter(Book.category_id == CustomerPurchase.book_store_category_id)\
.group_by(BookStore.book_amount, CustomerPurchase.book_store_category_id, Category.category_name, Category.unit_cost, Category.total_stock_amount, Book.stock_amount)

bp = bp.all()