我写了以下查询。
select distinct(table3.*),
(select count(*)
from table2
where table2.cus_id = table3.id) as count,
(select sum(amount)
from table2
where table2.cus_id = table3.id) as total
from table2,
table1,
table3
where table3.id = table2.cus_id
and table2.own_id = table1.own_id;
它找到列的总和,产生总和的行数以及来自另一个表的一些关联数据。 (如果您认为可以改进,请随意优化)
我需要将其转换为SQLAlchemy但不知道从哪里开始。我很感激任何建议。
答案 0 :(得分:3)
以下是我对您的查询的重写:
SELECT t3.*,
x.count,
x.amount
FROM TABLE3 t3
JOIN (SELECT t2.cus_id
COUNT(*) AS count,
SUM(t2.amount) AS total
FROM TABLE2 t2
WHERE EXISTS(SELECT NULL
FROM TABLE1 t1
WHERE t1.own_id = t2.own_id)
GROUP BY t2.cus_id) x ON x.cus_id = t3.id
抱歉,无法帮助您使用SQLAlchemy部分。