admin

带有子查询,分组依据,计数和求和功能的高级SQL查询到SQLalchemy

sql

我写了以下查询。

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


阅读 302

收藏
2021-06-07

共1个答案

admin

这是我对查询的重写:

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

2021-06-07