Python Sqlalchemy嵌套查询返回错误的数据

Python Sqlalchemy嵌套查询返回错误的数据,python,sql,postgresql,sqlalchemy,nested,Python,Sql,Postgresql,Sqlalchemy,Nested,我有一个SQL表达式: SELECT count(*), date_trunc('day', data) from ( select max(hc.acesso) as data from historico_comunicacao hc join cliente c on (c.id = hc.id_cliente) group by c.id having max(hc.acesso) between ('2012-11-30') and ('2012-12-07 23:59:59') o

我有一个SQL表达式:

SELECT count(*), date_trunc('day', data)
from (
select max(hc.acesso) as data 
from historico_comunicacao hc
join cliente c on (c.id = hc.id_cliente)
group by c.id
having max(hc.acesso) between ('2012-11-30') and ('2012-12-07 23:59:59')
order by max(hc.acesso) desc
) as x


GROUP BY 2
ORDER BY 2 DESC;
所以,我在SqlAlchemy中这样做了:

nestedQuery = session.query(func.max(MapComunicacao.acesso).label('data'))\
.join(MapCliente)\
.group_by(MapCliente.id)\
.having(func.max(MapComunicacao.acesso).between(dataini, dataFinal))\
.order_by(desc(func.max(MapComunicacao.acesso)))

query = session.query(
    func.count(nestedQuery.subquery().columns.data),
        extract('day', nestedQuery.subquery().columns.data)
)\
.group_by('anon_3.data')


result = query.all()
没有发生错误,但返回的数据对我来说是错误的

我有两张桌子:客户(Customer)和Historico_Acesso(Access_History)。我想知道的是上次与我的数据库通话的客户总数,按日期分组

像这样:

总日期

十九,;“2012-12-07 00:00:00+00”

十六,;“2012-12-06 00:00:00+00”

二十,;“2012-12-05 00:00:00+00”

06;“2012-12-04 00:00:00+00”

06;“2012-12-03 00:00:00+00”

01;“2012-12-02 00:00:00+00”

04;“2012-12-01 00:00:00+00”


09;“2012-11-30 00:00:00+00”

胡乱猜测:尝试将
nestedQuery.subquery()
提取到变量中,以便只调用一次

如果这不起作用,SQLAlchemy将很乐意使用
printquery
为您打印生成的SQL。然后可以与手工编制的SQL查询进行比较