使用三个表创建嵌套子查询

Creating a nested subquery with three tables

我有下面提到的 3 个表。每个部分都有两个与之关联的扫描。

首先需要找到我用下面的代码完成的每个社区中的部分。然后我需要找到每个社区每个部分的扫描总容量 (sum(cap_a+cap_b))。

我们想要的是一个列出街区和街区内各路段总容量的选择。

我一直在研究子查询,但我想不出这个问题的语法。

https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-subquery/

neighborhood (id,name,geom) 
sections (section,geom
scans (section,cap_a,cap_b)

SELECT neighborhood.name, sections.section
FROM neighborhood,sections
WHERE ST_WITHIN(section.geom,neighborhood.geom)

SELECT section,SUM(cap_a+cap_b) AS capacity
        FROM scans

到目前为止我已经进行了此查询,但没有给出我想要的正确结果。

SELECT
    neighborhood.id,
    neighborhood .name,
    capcity_of_neighborhood
FROM    
    neighborhood,
    section,
    scan
JOIN (
        SELECT section,SUM(cap_a+cap_b) AS capacity
        FROM scans
        GROUP BY section
    ) AS capcity_of_neighborhood 
ON capcity_of_neighborhood.section = scans.section
WHERE 
    ST_WITHIN(section.geom,neighborhood.geom)
GROUP BY 1,2,3
;

希望我正确理解您的查询。试试这个:

  SELECT ne.id
       , ne.name,
       , sc.capacity_total 
    FROM neighborhood ne
    JOIN section se
      ON ST_WITHIN(se.geom, ne.geom)
    JOIN (
            SELECT section
                 , SUM(cap_a+cap_b) AS capacity_total
              FROM scans
             GROUP 
                BY section
         ) AS sc
      ON sc.section = se.section
    ;