0

我有这个 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()

没有发生错误,但返回的数据对我来说是错误的。

我有两个表:Cliente (Customer) 和 Historico_Acesso (Access_History)。我想知道的是最后一次与我的数据库交谈的客户总数,按日期分组。

像这样:

总日期

19; “2012-12-07 00:00:00+00”

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

20; “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”

4

1 回答 1

1

Wild guess: try to extract nestedQuery.subquery() into a variable, so that it's called only once.

If that doesn't work, SQLAlchemy will gladly print the generated SQL for you with print query. You can then compare with your handcrafted SQL query.

于 2012-12-20T12:13:33.270 回答