如何将条件语句的结果传递给另一个 SQL 语句?

How to pass results of conditional statement to another SQL statement?

以下 SQL 使用 PostgreSQL 中的 PostGIS 扩展执行以下工作流:

  1. 为此示例制作一些示例多边形
  2. 在每个多边形中创建 1000 个随机点
  3. 将每个多边形中的随机点聚类为 4 个聚类

我想添加一个条件语句,以便每个多边形的面积决定要制作多少个聚类,而不是为每个多边形设定数量。

这里是根据面积判断簇数的条件语句:

--Conditional statement
SELECT poly_id,
    CASE
      WHEN ST_Area(geom) > 9 THEN 1
      ELSE 0
    END
  FROM polys;

如何将此条件语句集成到应用聚类的 SQL 语句中?最终结果应该是多边形,每个多边形的聚类数量由多边形面积决定。


带有示例数据的完整 SQL 代码

-- Make up some data
CREATE TABLE polys(poly_id, geom) AS (
        VALUES  (1, 'POLYGON((1 1, 1 5, 4 5, 4 4, 2 4, 2 2, 4 2, 4 1, 1 1))'::GEOMETRY),
                (2, 'POLYGON((6 6, 6 10, 8 10, 9 7, 8 6, 6 6))'::GEOMETRY)
    );

-- Create point clusters within each polygon
CREATE TABLE pnt_clusters AS
  SELECT  polys.poly_id,
          ST_ClusterKMeans(pts.geom, 4) OVER(PARTITION BY polys.poly_id) AS cluster_id,
          pts.geom
  FROM    polys,
          LATERAL ST_Dump(ST_GeneratePoints(polys.geom, 1000, 1)) AS pts
;

编辑:

当我尝试组合 SQL 语句时,出现以下错误:

ERROR:  syntax error at or near "AS"
LINE 4: ...ans(pts.geom, 8) OVER(PARTITION BY polys.poly_id) AS cluster...

-- Create point clusters within each polygon
CREATE TABLE pnt_clusters3 AS
  SELECT  polys.poly_id,
      CASE
          WHEN ST_Area(geom) >9 THEN ST_ClusterKMeans(pts.geom, 8) OVER(PARTITION BY polys.poly_id) AS cluster_id,
          pts.geom
          ELSE ST_ClusterKMeans(pts.geom, 2) OVER(PARTITION BY polys.poly_id) AS cluster_id,
          pts.geom
      END
  FROM    polys,
          LATERAL ST_Dump(ST_GeneratePoints(polys.geom, 1000, 1)) AS pts
;

请查看对语法错误的更正:

-- Create point clusters within each polygon
CREATE TABLE pnt_clusters3 AS
  SELECT  polys.poly_id,
      CASE
          WHEN ST_Area(polys.geom) >9 THEN ST_ClusterKMeans(pts.geom, 8) OVER(PARTITION BY polys.poly_id) 
          
          ELSE ST_ClusterKMeans(pts.geom, 2) OVER(PARTITION BY polys.poly_id) 
         
      END AS cluster_id,
        pts.geom
  FROM    polys,
          LATERAL ST_Dump(ST_GeneratePoints(polys.geom, 1000, 1)) AS pts
;