SqlAlchemy查询/合并行

时间:2017-08-01 12:35:11

标签: sql database postgresql python-3.x sqlalchemy

我必须在表格中搜索行并合并它们和teir值。

示例:

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

所以我想得到这样的结果:

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()

1 个答案:

答案 0 :(得分: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执行类似操作。