来自CASE的意外结果引用另一个表达式

时间:2014-12-22 22:08:29

标签: sql postgresql postgis

以下语句始终返回st_area(st_buffer(polygon,100))的结果。

select st_Area(polygon) as area,
case when area>100000 then st_area(st_buffer(polygon,500))
else st_area(st_buffer(polygon,100))
end from polygons limit 10;

       area       |     st_area
------------------+------------------
 383287.287473659 | 723738.615102036
 47642.5395246768 | 192575.823383778
  45546.753026985 | 174122.420564731
 435204.455923533 | 725419.735987631
 839954.564052786 | 1268251.88626391
  315213.27742828 | 630424.785088617
 966620.061916605 | 1447647.57269461
 38446.6010009923 | 151584.647252579
 82576.1182937309 | 238095.988431594
 321682.125463567 | 695462.262796463
(10 rows)

st_area应该是st_buffer(polygon,500) area>100000的结果,如下所示:

     area      |     st_area
------------------+------------------
 383287.287473659 | 2702203.34758147
 47642.5395246768 | 192575.823383778
  45546.753026985 | 174122.420564731
 435204.455923533 | 2507469.89929028
 839954.564052786 | 3568866.96452707
  315213.27742828 | 2453576.33477712
 966620.061916605 | 3953365.12876066
 38446.6010009923 | 151584.647252579
 82576.1182937309 | 238095.988431594
 321682.125463567 | 2628693.69179652
(10 rows)

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

这个问题尚未完全清楚,但我受过教育的猜测是你想要的:

SELECT st_Area(polygon) AS area  -- or pick some other name!
     , CASE WHEN st_Area(polygon) > 100000
            THEN st_area(st_buffer(polygon,500))
            ELSE st_area(st_buffer(polygon,100)) END AS st_area
FROM   polygons
LIMIT  10;

您无法在同一SELECT列表的其他项目中引用列别名( 输出 列的名称)。您只能引用 输入 列名称。所以你必须重复表达式或使用子查询:

SELECT area
     , CASE WHEN area > 100000
            THEN st_area(st_buffer(polygon,500))
            ELSE st_area(st_buffer(polygon,100)) END AS st_area
FROM (SELECT st_Area(polygon) AS area, polygon FROM polygons LIMIT 10) sub;

通常,您应该立即收到语法错误。显然,您的基表中还有另一列名为area的列。因此混乱。额外的智慧可以带走这个:

  • 将别名附加到输出列时,最好使用与任何输入列不同的名称。
  • 始终在问题中包含表格定义。澄清很多