你好?我试图在SQLAlchemy中写一个查询(有2个子查询),但出现错误AttributeError:'list'对象没有属性'l_date'
这是我的代码:
import sqlalchemy as db
from sqlalchemy import func
from sqlalchemy import desc
from sqlalchemy.orm import sessionmaker
from sqlalchemy import or_
from sqlalchemy import and_
from sqlalchemy.sql.expression import alias
try:
engine = db.create_engine('postgresql://user:pass@localhost:5432/db_name')
connection = engine.connect()
except:
print('Error establishing DB connection')
# Import metadata
metadata = db.MetaData()
# create a configured "Session" class
Session = sessionmaker(bind=engine)
# create a Session
session = Session()
# Import articles, authors and log tables
log = db.Table('log', metadata, autoload=True, autoload_with=engine)
def days_with_request_errors():
query1 = db.select([func.DATE(log.columns.time).label('l_date'), func.count(log.columns.status).label('s_count')]) \
.where(or_(log.columns.status.like('%5%'), log.columns.status.like('%4%'))) \
.group_by(func.DATE(log.columns.time))
ResultProxy = connection.execute(query1)
q1 = ResultProxy.fetchall()
query2 = db.select([func.DATE(log.columns.time).label('l_date'),
func.count(log.columns.status).label('s_count')]) \
.group_by(func.DATE(log.columns.time))
ResultProxy = connection.execute(query2)
q2 = ResultProxy.fetchall()
main_query = db.select([q1.l_date, (q1.s_count * 100) / q2.s_count]) \
.where(q1.l_date == q2.l_date) \
.where(and_((q1.c.s_count * 100) / q2.c.s_count) > 1)
ResultProxy = connection.execute(main_query)
return ResultProxy.fetchall()
这是我正在转移到SQLAlchemy的原始SQL查询。 (原始查询工作正常):
SELECT q1.date, ((q1.count * 100) / q2.count) as percentage
FROM (SELECT date(time) as date, COUNT(status) as count
FROM log
WHERE status LIKE '%4%' or status LIKE '%5%'
GROUP BY date(time)) as q1,
(SELECT date(time) as date, COUNT(status) as count
FROM log
GROUP BY date(time)) as q2
WHERE q1.date = q2.date and ((q1.count * 100) / q2.count) > 1
任何帮助将不胜感激。
答案 0 :(得分:0)
我弄清楚出了什么问题。子查询缺少别名。为了使其正常工作,我对子查询进行了如下修改:
query1 = db.select([func.DATE(log.columns.time).label('l_date'), func.count(log.columns.status).label('s_count')]) \
.where(or_(log.columns.status.like('%5%'), log.columns.status.like('%4%'))) \
.group_by(func.DATE(log.columns.time)).alias('query1')
query2 = db.select([func.DATE(log.columns.time).label('l_date'),
func.count(log.columns.status).label('s_count')]) \
.group_by(func.DATE(log.columns.time)).alias('query2')