简体   繁体   English

如何在flask-sqlalchemy的单行中同时包含SELECT语句中的SUM和COUNT

[英]How to include both SUM, COUNT in SELECT statement in a single line in flask-sqlalchemy

I'm very new to the programming world. 我对编程世界很陌生。 Recently, I've been trying to rewrite sqlite codes in python 3.6 to flask-sqlalchemy and I'd like to know how to rewrite the following code in flask-sqlalchemy in a single statement and pass the selected values into a single variable just as in the code: 最近,我一直在尝试将python 3.6中的sqlite代码重写为flask-sqlalchemy ,我想知道如何在单个语句中将flask-sqlalchemy 的以下代码重写,并将选择的值传递给单个变量 ,就像在代码中:

rows = db.execute("SELECT SUM(student_total) AS stdtotal, SUM(payment_total) AS paytotal, COUNT(identifier) AS clstotal FROM classes WHERE admin_id = :admID", admID=session["user_id"]) rows = db.execute(“ SELECT SUM(student_total)AS stdtotal,SUM(payment_total)AS paytotal,COUNT(identifier)AS clstotal FROM类WHERE admin_id =:admID”,admID = session [“ user_id”])

I have read this: http://wiki.workassis.com/sum-avg-count-max-group_by-distinct-sqlalchemy/ but I need to import func from sqlalchemy and if possible, I wish to avoid doing so. 我已阅读以下内容: http ://wiki.workassis.com/sum-avg-count-max-group_by-distinct-sqlalchemy/,但我需要从sqlalchemy导入func,如果可能,我希望避免这样做。

Thank you very much in advance. 提前非常感谢您。

I have solved it, thanks to Ilja Everilä's comment and some further readings. 感谢IljaEverilä的评论和进一步的阅读,我已经解决了它。 I tried using the func library and it works. 我尝试使用func库,并且可以正常工作。 I guess it's not possible for me to avoid using func. 我想我不可能避免使用func。 For the new flask-sqlalchemy users who may encounter the same problem as I did in the future, I will write out the solution that I have come up with: 对于可能与我将来遇到相同问题的新flask-sqlalchemy用户,我将写出我想出的解决方案:

Note: This solution needs to import label from sqlalchemy.sql 注意:此解决方案需要从sqlalchemy.sql导入标签

rows = db.session.query(label('stdtotal', db.func.sum(classes.student_total)), label('paytotal', db.func.sum(classes.payment_total)), label('clstotal', db.func.count(classes.identifier))).filter_by(admin_id=session["user_id"]) 行= db.session.query(label('stdtotal',db.func.sum(classes.student_total)),label('paytotal',db.func.sum(classes.payment_total)),label('clstotal', db.func.count(classes.identifier)))。filter_by(admin_id =会话[ “USER_ID”])

**Please note that the type of the return value of the above query is not the same as that of the sqlite SELECT statement. **请注意,上述查询的返回值类型与sqlite SELECT语句的返回值类型不同。 For sqlite, the return value is a dictionary but for the flask-sqlalchemy, the return value is an object. 对于sqlite,返回值是一个字典,但是对于flask-sqlalchemy,返回值是一个对象。 (See http://docs.sqlalchemy.org/en/latest/orm/query.html ) (请参阅http://docs.sqlalchemy.org/en/latest/orm/query.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM