Sqlalchemy核心 - 在联合查询中使用func.sum

时间:2018-02-14 10:31:01

标签: python function sqlalchemy sum union

我正在尝试找出如何对union_all选择的结果求和。我可以在个别选择中使用sum函数,但不能使用它们的并集。

union_all(
    select([first.c.amount]).
        where(first.c.player_id == player_id).

    select([second.c.amount]).
        where(second.c.player_id == player_id).

    select([third.c.amount]).
        where(third.c.player_id == player_id).

    select([fourth.c.amount]).
        where(fourth.c.player_id == player_id).
)

1 个答案:

答案 0 :(得分:0)

将union的(别名)视为可选择,只需选择金额之和:

In [15]: u = union_all(
    ...:     select([first.c.amount]).
    ...:         where(first.c.player_id == player_id),
    ...: 
    ...:     select([second.c.amount]).
    ...:         where(second.c.player_id == player_id),
    ...: 
    ...:     select([third.c.amount]).
    ...:         where(third.c.player_id == player_id),
    ...: 
    ...:     select([fourth.c.amount]).
    ...:         where(fourth.c.player_id == player_id)
    ...: ).alias()

In [16]: stmt = func.sum(u.c.amount).select()

In [17]: print(stmt)
SELECT sum(anon_1.amount) AS sum_1 
FROM (SELECT first.amount AS amount 
FROM first 
WHERE first.player_id = :player_id_1 UNION ALL SELECT second.amount AS amount 
FROM second 
WHERE second.player_id = :player_id_2 UNION ALL SELECT third.amount AS amount 
FROM third 
WHERE third.player_id = :player_id_3 UNION ALL SELECT fourth.amount AS amount 
FROM fourth 
WHERE fourth.player_id = :player_id_4) AS anon_1