2010-11-01 95 views
2

我已经写了下面的查询。高级SQL查询与子查询,分组数,总和函数SQLalchemy

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,但不知道从哪里开始。我会很感激任何建议。

回答

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的一部分,对不起。

+0

太棒了 - 您的查询更好!只需要将它转换为SQLAlchemy - 任何接受者? :-) – eski009 2010-11-02 11:26:47