【问题标题】:How to pass results of conditional statement to another SQL statement?如何将条件语句的结果传递给另一个 SQL 语句?
【发布时间】:2020-10-24 02:58:05
【问题描述】:

以下 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
;

【问题讨论】:

  • 如果我明白了,如果 ST_Area(geom)>9 else 2,您希望用 1 替换您的 ", 4"。对吗?
  • @AndreaTaroni86 是的,没错。

标签: sql postgresql conditional-statements case postgis


【解决方案1】:

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

-- 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
;

【讨论】:

  • 感谢您的回答。此部分产生以下错误:ERROR: column reference "geom" is ambiguous LINE 4: WHEN ST_Area(geom) >9 THEN ST_ClusterKMeans(pts.ge...
  • @Borealis 我已经更新了答案。很高兴你让它工作
猜你喜欢
  • 2020-02-10
  • 2013-06-10
  • 2017-02-17
  • 2021-11-03
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2013-12-03
相关资源
最近更新 更多