2017-08-01 120 views
0

我必須搜索表中的行併合並它們和teir值。SqlAlchemy查詢/合併行

例子:

id_sender id_receiver nb_mails 
    3   4   10 
    1   2   13 
    4   3   5 

,所以我想這樣的resultat:

id_1 id_2 nb_communication 
3  4  15 
1  2  13 

是否有可能與SQLAlchemy的完成,或者我需要做我自己的治療方法?

解決了:

q = session.query(
        label('id_1' ,func.least(table.initiator_id, table.receiver_id)), 
        label('id_2', func.greatest(table.initiator_id, table.receiver_id)), 
        label('nb_communication', func.sum(table.nb_mails)) 
       ).order_by("nb_communication").group_by('id_1', 'id_2').all() 
+0

用你正在使用的數據庫標記你的問題。 –

+0

通常,如果它在SQL中可行,它在SQLAlchemy中是可行的。你有嘗試過什麼嗎? –

+1

yes試過這個東西,它做了我的工作: q = session.query( label('id_1',func.least(table.initiator_id,table.receiver_id)), label('id_2',func.greatest (table.initiator_id,table.receiver_id)), label('nb_communication',func.count(table.nb_mails)) ).order_by(「nb_communication」).group_by('id_1','id_2')。all ) – xsimsiotx

回答

1

大多數數據庫支持least()greatest()功能。你可以這樣做:

select least(id_sender, id_receiver) as id_1, 
     greatest(id_sender, id_receiver) as id_2, 
     sum(nb_mails) as nb_communication 
from t 
group by least(id_sender, id_receiver), 
     greatest(id_sender, id_receiver); 

如果你的數據庫不支持這些功能,您可以使用case做類似的事情。

+0

謝謝,這幫助我找到一個想法來解決sqlalchemy我的問題 – xsimsiotx