【问题标题】:Advanced SQL query with sub queries, group by, count and sum functions in to SQLalchemySQLalchemy 中带有子查询、分组、计数和求和功能的高级 SQL 查询
【发布时间】:2010-11-01 23:20:15
【问题描述】:

我已经编写了以下查询。

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

【问题讨论】:

    标签: python sql postgresql sqlalchemy


    【解决方案1】:

    这是我对您的查询的重写:

    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 部分无法帮助您,抱歉。

    【讨论】:

    • 太棒了 - 您的查询要好得多!只需要将其转换为 SQLAlchemy - 任何接受者? :-)
    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 2019-07-22
    • 2014-02-27
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多