SQLalchemy 中带有子查询、分组依据、计数和求和函数的高级 SQL 查询

发布于 2024-09-30 08:52:49 字数 497 浏览 1 评论 0原文

我写了以下查询。

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

I have written the following query.

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;

It finds the sum of a column and the number of rows that produce the sum as well as some associated data from another table. (Feel free to optimise if you think it can be improved)

I need to convert this in to SQLAlchemy but have no idea where to start. I'd appreciate any advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蔚蓝源自深海 2024-10-07 08:52:49

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

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 部分。

Here's my re-write of your query:

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

Can't help you with the SQLAlchemy part, sorry.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文